/*********** Begin Core Function ***********/

function $id(id){
	return typeof(id)=="string"?document.getElementById(id):id;
};

function $extend(){
	// copy reference to target object
	var target = arguments[0] || {}, i = 1, length = arguments.length, options;
	// Handle case when target is a string or something (possible in deep copy)
	if ( typeof target != "object" && typeof target != "function" )
		target = {};
	for ( ; i < length; i++ )
		// Only deal with non-null/undefined values
		if ( (options = arguments[ i ]) != null )
			// Extend the base object
			for ( var name in options ) {
				var copy = options[ name ];
				// Prevent never-ending loop
				if ( target === copy )
					continue;
				if ( copy !== undefined )
					target[ name ] = copy;
			}
	// Return the modified object
	return target;
};

function $namespace(str){
    var arr=str.split(',');
    for(var i=0,len=arr.length;i<len;i++){
        // 将命名空间切成N部分, 比如mini、common等
        var    arrJ=arr[i].split("."),parent={};
        for (var j = 0,jLen=arrJ.length; j < jLen; j++){
            var name = arrJ[j],child=parent[name];
            j===0?eval('(typeof '+name+')==="undefined"?('+name+'={}):"";parent='+name):(parent=parent[name]=(typeof child)==='undefined'?{}:child);
        };
    }
};

function $display(ids,state){
	var state=state||'';
	if(typeof(ids)=="string"){
		var arr=ids.split(',');
		
		for(var i=0,len=arr.length;i<len;i++){
			var o=$id(arr[i]);
			o?o.style.display=state:'';
		}	
	}else{ids.style.display=state}
};

function $isFloat(v){
	//浮点数
	return /^(([1-9]\d*)|(\d+\.\d+)|0)$/.test(v); 
};

function $isRange(v,min,max){
	//注意，这里的undefined不能加上引号
	if(min!=null&&max!=null){
		return v>=min&&v<=max;
	}else if(min!=null){
		return v>=min;
	}else if(max!=null){
		return v<=max;
	}else{return true}
}

function $strLenGB(v){
	//一个中文按照两个字节算，返回长度
	return v.replace(/[\u00FF-\uFFFF]/g,"  ").length;
};

function $val(findstr){
	var objs=$$(findstr);
	var returnvar=[];
	for(var i=0;i<objs.length;i++){
		var t=objs[i];
		if(t.tagName.toLowerCase()=="input"){
			if((t.type.toLowerCase()=="checkbox" || t.type.toLowerCase()=="radio") ){	//设置单选复选框的值
				if(t.checked==true){
					returnvar.push(t.value);
				}
			}else{
				returnvar.push($$(t).val());
			}
		}else if(t.tagName.toLowerCase()=="select"){
			returnvar=returnvar.concat($$(t).val());
		}else{
			returnvar.push($$(t).val());
		}
	}
	returnvar=$$.grep(returnvar,function(n,i){return n!=null;});
	return returnvar;
};

function $arrayUniq(arr){
	var returnArr=[];
	for (var i=0,len=arr.length;i<len;i++){
		((","+returnArr+",").indexOf(","+arr[i]+",")<0)?returnArr.push(arr[i]):'';
	};
	return returnArr;	
}

function $loadScript(url,id,obj){
	//创建一个script并加载script
	//参数：id:'放置script的id',url:'载入的地址'
	setTimeout(function(){
		var s = document.createElement("script"),
			time=new Date().getTime(),			
			o=obj||{},			
			charset=o.charset|| "gb2312";
		id= id?(id+time):time,
		url=o.isToken!==false?$addToken(url,"ls"):url;
		s.charset=charset;
		s.id = id;
		document.getElementsByTagName("head")[0].appendChild(s);
		s.src = url;
		return s;
	},0);
};

function $loadCss(path){
	if(!window["_loadCss"+path]){
			var l = document.createElement('link');
			l.setAttribute('type', 'text/css');
			l.setAttribute('rel', 'stylesheet');
			l.setAttribute('href', path);
			l.setAttribute("id","loadCss"+Math.random());
			document.getElementsByTagName("head")[0].appendChild(l);
			window["_loadCss"+path]=true;
	}
	return true;
}

function $getPageScrollHeight(){
	var bodyCath=document.body;
	var doeCath=document.compatMode=='BackCompat'?bodyCath:document.documentElement;
	return (window.MessageEvent && navigator.userAgent.toLowerCase().indexOf('firefox')==-1)?bodyCath.scrollTop:doeCath.scrollTop;
}

function $getPageScrollWidth(){
	var bodyCath=document.body;
	var doeCath=document.compatMode=='BackCompat'?bodyCath:document.documentElement;
	return (window.MessageEvent&&navigator.userAgent.toLowerCase().indexOf('firefox')==-1)?bodyCath.scrollLeft:doeCath.scrollLeft;
}

function $getWindowHeight(){
	var bodyCath=document.body;
	return (document.compatMode=='BackCompat'?bodyCath:document.documentElement).clientHeight;
}

function $getWindowWidth(){
	var bodyCath=document.body;
	return (document.compatMode=='BackCompat'?bodyCath:document.documentElement).clientWidth;
}

function $getContentHeight(){
//获取页面内容的实际高度
var bodyCath=document.body;
var doeCath=document.compatMode=='BackCompat'?bodyCath:document.documentElement;
return (window.MessageEvent&&navigator.userAgent.toLowerCase().indexOf('firefox')==-1)?bodyCath.scrollHeight:doeCath.scrollHeight;
}

function $getContentWidth(){
//获取页面内容的实际宽度
	var bodyCath=document.body;
	var doeCath=document.compatMode=='BackCompat'?bodyCath:document.documentElement;
	return (window.MessageEvent&&navigator.userAgent.toLowerCase().indexOf('firefox')==-1)?bodyCath.scrollWidth:doeCath.scrollWidth;
}

function $getX(e){
//获取页面中对象的绝对X位置
	var t=e.offsetLeft;
	while(e=e.offsetParent)t+=e.offsetLeft;
	return t;
}

function $getY(e){
//获取页面中对象的绝对Y位置
	var t=e.offsetTop;
	while(e=e.offsetParent){
		t+=document.body!=e?e.offsetTop:0;
	}
	return t;
}

function $getQuery(name,url){
//参数：变量名，url为空则表从当前页面的url中取
	var u  = arguments[1] || window.location.search,
		reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"),
		r = u.substr(u.indexOf("\?")+1).match(reg);
	return r!=null?r[2]:"";
};

function $displayHide(ids){
	$display(ids,'none');
};

function $delCookie(name){
//删除cookie
	var exp = new Date(); 
	exp.setTime(exp.getTime() - 1);
	var cval=$getCookie(name);
	document.cookie= name + "="+cval+";expires="+exp.toGMTString();
};

function $onReady(fn) { 
	//document的ready事件
	var d = document;
	var done = false, 
	init = function () { 
		if (!done){
			done = true; 
			fn(); 
		} 
	};
	(function () { 
		try { 
			d.documentElement.doScroll('left'); 
		} catch (e) { 
			setTimeout(arguments.callee, 50); 
			return; 
		} 
		init(); 
	})(); 
	d.onreadystatechange = function() { 

		if (d.readyState == 4) { 
			d.onreadystatechange = null; 
			init(); 
		} 
	}; 
};

function $getScrollPosition(){
	//获取滚动条的位置
	var pos=[];
	if(typeof window.pageXOffset!="undefined"){
		pos=[window.pageXOffset,window.pageYOffset];
	}else if(document.body&&typeof document.body!="undefined"){
		pos=[document.body.scrollLeft,document.body.scrollTop];
	}else{
		pos=[document.documentElement.scrollLeft,document.documentElement.scrollTop];
	}
	return pos;
};

function $getMousePosition(e){
	//获取鼠标的位置
	var e=window.event?window.event:e.evt;
	var pos=[];
	if(typeof e.pageX!="undefined"){
		pos=[e.pageX,e.pageY];
	}else if(typeof e.clientX!="undefined"){
		pos=[e.clientX+$getScrollPosition()[0],e.clientY+$getScrollPosition()[1]];
	}
	return pos;
}

function $initDragItem(obj){
	//控制组件拖动方法
	var option = {
		barDom: "", //拖动区域的dom对象
		targetDom: "" //被拖动区域的dom对象
	};
	for (var i in obj) {
		option[i] = obj[i];
	}
	window._dragOption ? "" : window._dragOption = {};
	//设置状态
	option.barDom.style.cursor = 'move';
	option.targetDom.style.position = "absolute";
	option.barDom.onmousedown = function(e){
		var e = window.event || e;
		window._dragOption.barDom = this;
		window._dragOption.targetDom = option.targetDom;
		var currPostion = [parseInt(option.targetDom.style.left) ? parseInt(option.targetDom.style.left) : 0, parseInt(option.targetDom.style.top) ? parseInt(option.targetDom.style.top) : 0];
		window._dragOption.diffPostion = [$getMousePosition({
			evt: e
		})[0] - currPostion[0], $getMousePosition({
			evt: e
		})[1] - currPostion[1]];
		document.onselectstart = function(){
			return false
		};
		window.onblur = window.onfocus = function(){
			document.onmouseup()
		};
		return false;
	};
	option.targetDom.onmouseup = document.onmouseup = function(){
		if (window._dragOption.barDom) {
			window._dragOption = {};
			document.onselectstart = window.onblur = window.onfocus = null;
		}
	};
	option.targetDom.onmousemove = document.onmousemove = function(e){
		try {
			var e = window.event || e;
			if (window._dragOption.barDom && window._dragOption.targetDom) {
				window._dragOption.targetDom.style.left = ($getMousePosition({
					evt: e
				})[0] - window._dragOption.diffPostion[0]) + "px";
				window._dragOption.targetDom.style.top = ($getMousePosition({
					evt: e
				})[1] - window._dragOption.diffPostion[1]) + "px";
			}
		} 
		catch (e) {
		}
	};
}

function $strReplace(str,re,rt){
	//同时支持json格式的批量替换和原始的全部替换
	if(rt!=undefined){
		replace(re,rt);
	}else{
		for(var key in re){
			replace(key,re[key]);
		};
	};
	
	function replace(a,b){
		var arr=str.split(a);
		str=arr.join(b);
	};

	return str;
};

function $isDocReady(){
	//判断页面是否ready
	if(navigator.userAgent.match(/MSIE/)){
		try{
			document.documentElement.doScroll('left');
			return true;              
		}catch(e){}
		return false;
	}else{
		return document.body?true:false;
	}
}

function $formatDate(date,formatStr){ 
	//格式化时间
	var	arrWeek=['日','一','二','三','四','五','六'],
		str=formatStr
			.replace(/yyyy|YYYY/,date.getFullYear())
			.replace(/yy|YY/,$addZero(date.getFullYear()%100,2)	)
			.replace(/mm|MM/,$addZero(date.getMonth()+1,2))
			.replace(/m|M/g,date.getMonth()+1)
			.replace(/dd|DD/,$addZero(date.getDate(),2)	)
			.replace(/d|D/g,date.getDate())
			.replace(/hh|HH/,$addZero(date.getHours(),2))
			.replace(/h|H/g,date.getHours())
			.replace(/ii|II/,$addZero(date.getMinutes(),2))
			.replace(/i|I/g,date.getMinutes())
			.replace(/ss|SS/,$addZero(date.getSeconds(),2))
			.replace(/s|S/g,date.getSeconds())
			.replace(/w/g,date.getDay())
			.replace(/W/g,arrWeek[date.getDay()]); 
	return str; 
};

function $strTrim(str,code){
//删除字符串两端的空格或者指定内容
	var argus  = code || "\\s";
	var temp = new RegExp("(^"+argus+"*)|("+argus+"*$)","g");
	return str.replace(temp,"");
}

function $setCookie(name,value,expiresd,path,domain,secure){
	//写入COOKIES
	var expdate = new  Date(),
		expires = arguments[2] || null,
		path  	= arguments[3] || "/",
		domain  = arguments[4] || null,
		secure  = arguments[5] || false;		
	expires?expdate.setMinutes(expdate.getMinutes() + parseInt(expires)):"";		
	var cookietemp =escape(name) + '=' + escape(value) + (expires ? '; expires=' + expdate.toGMTString() : '') + (path ? '; path=' + path : '')+ (domain ? '; domain=' + domain : '')+(secure ? '; secure' : '');
	document.cookie=cookietemp;
};

function $addEvent(obj,type,handle){
	//事件绑定，兼容ff，ie
	if (window.addEventListener){
		obj.addEventListener(type, handle, false);
	}else if (window.attachEvent){
		obj.attachEvent("on"+type, handle);
	}else{
		obj["on" + type] = handle; 
	}
};

function $regionGetIdByProvinceName(Prov){
	//根据省的名字获取省的id
	var regionMap=$getRegionMap();
	for(var i in regionMap){
		if(Prov==regionMap[i][0]){
			return i;
		}
	}
	return "";
}

function $regionGetPath(rid){
	//根据地址id获取地址的省市区的路径,返回对象结构:[省id，省名称，市id，市名称，地区id，地区名称，是否是一个完整有效的地址结果]
	var regionMap=$getRegionMap();
	var regionPath=["","","","","","",false];
	if(!(parseInt(rid)>=0)){
		return regionPath;
	}
	for(var i in regionMap){
		if(i.toString()==rid.toString()){
			//如果直接在省一级找到了，就直接返回路径结果
			regionPath=[i,regionMap[i][0],"","","","",true];
			return regionPath;
		}else{
			//把省的id放入数组，并从这个省开始查找所有市的匹配
			regionPath[0]=i;
			regionPath[1]=regionMap[i][0];
			//匹配当前省里面的所有市
			for(var j in regionMap[i][2] ){
				//如果匹配到了市，就返回新的路径
				if(j.toString()==rid.toString()){
					regionPath=[regionPath[0],regionPath[1],j,regionMap[i][2][j][0],"","",true];
					return regionPath;
				}else{
					//当前市写入路径，做记忆
					regionPath[2]=j;
					regionPath[3]=regionMap[i][2][j][0];
					//如果匹配不到就到这个市的地区信息里面匹配
					for(var k in regionMap[i][2][j][2]){
						//如果匹配到了地区，就返回新的路径,匹配不到就什么也不做
						if(k.toString()==rid.toString()){
							regionPath=[regionPath[0],regionPath[1],regionPath[2],regionPath[3],k,regionMap[i][2][j][2][k][0],true];
							return regionPath;
						}
					}
					//如果走到这里就表示当前市的地区都不合适，要返回上一级循环去匹配下一个市。我们清空路径中当前市的id
					regionPath[2]="";
					regionPath[3]="";
				}
			}
			//如果走到这里，但当前省里面的所有市里都找不目标地址的配置，要返回上一级循环，去匹配下一个省，我们清空路径中的当前省
			regionPath[0]="";
			regionPath[1]="";
		}
	}
	//如果走到这里，则标识从整个地址信息中都匹配不到目标地址，数据是无效的，我们直接返回空路径
	return regionPath;
};

function $formatPrix(prix,formatStr){
	//格式化价格，注意JS是没有四舍五入的，只能直接截取
	//formatStr:x.x,x.xx,x.xxx……
	var arrPrix=[];
	
	prix=prix+"";//转为字符串
	var arr=prix.split(".");
	arr[1]=arr[1]||"";//如果没有传入小数后面的值，也保证arr[1]存在。
	var arrLen=arr[1].length;
	
	var arrFormat=formatStr.split(".");
	arrFormat[1]=arrFormat[1]||"";
	var formatLen=arrFormat[1].length;
	
	if(formatLen==0){return [arr[0]]};
	
	if(formatLen<=arrLen){
		arr[1]=arr[1].substr(0,formatLen);
	}else{
		var lessLen=formatLen-arrLen;
		for(var i=0;i<lessLen;i++){		
			arr[1]+="0";
		}
	};
	
	return [arr[0]+"."+arr[1],arr[0],arr[1]];
};

function $regionGetPathByStr(rstr){
	//根据地址描述（如：湖北省武汉市黄陂区）获取地址的省市区的路径,返回对象结构同$regionGetPath
	var regionMap=$getRegionMap();
	var regionArr=["","","","","","",false,""];
	if(!rstr) return;
	if(rstr.indexOf("省", 0) != -1){
		rstr = rstr.replace("省", "");
	}
	var special=[[0,"北京北京市",40000,"北京","北京市"],[1,"天津天津市",100,"天津","天津市"],[2,"上海上海市",200,"上海","上海市"],[3,"重庆重庆市",300,"重庆","重庆市"]];
	for(var i=0;i<special.length;i++){
		var data=special[i];
		if(regionMap[data[0]][0]==rstr.substring(0,2)){
			rstr=rstr.replace(data[1],"");
			for(var s in regionMap[data[0]][2][data[2]][2]){
				if(regionMap[data[0]][2][data[2]][2][s]==rstr){
					return [data[0],data[3],data[2],data[4],s,rstr,true,s];
				}
			}
		}
	}
		
	if(regionMap[42245][0] == rstr.substring(0,2)){
		regionArr = [42245, "海外", 42246, "海外", "", "", true, 42246];
	}
	special=[[32,"香港"],[33,"澳门"],[31,"台湾"]];
	for(var i=0;i<special.length;i++){
		var data=special[i];
		if(regionMap[data[0]][0]==rstr.substring(0,2)){
			rstr=rstr.replace(data[1],"");
			for(var s in regionMap[data[0]][2]){
				if(regionMap[data[0]][2][s][0]==rstr){
					return regionArr=[data[0],data[1],s,rstr,"","",true,s]
				}
			}
		}
	}
	if((rstr.substring(0,3) === (regionMap[10][0]) || (rstr.substring(0,3) === regionMap[6][0]))){
			regionArr[0] = index =  (rstr.substring(0,3) === "黑龙江") ?  6 : 10;
			regionArr[1] = (rstr.substring(0,3) === "黑龙江") ? regionMap[6][0] : regionMap[10][0];
			rstr = rstr.replace(rstr.substring(0,3), "");
			for(var s in regionMap[index][2]){
				if(rstr.substring(0, 2) === (regionMap[index][2][s][0]).substring(0, 2) ){
					regionArr[2] = s;
					regionArr[3] = regionMap[index][2][s][0];
					rstr = rstr.replace(regionMap[index][2][s][0], "");
					for(var k in regionMap[index][2][s][2]){
						if(regionMap[index][2][s][2][k][0] === rstr){
							regionArr[4] = k;
							regionArr[5] = regionMap[index][2][s][2][k][0];
							regionArr[6] = true;
							regionArr[7] = k;
						}
					}
				}
			}
	}
	for(var i in regionMap){
		if((regionMap[i][0]).substring(0,2) === rstr.substring(0,2)){
			regionArr[0] = i;
			regionArr[1] = regionMap[i][0];
			rstr = rstr.replace(rstr.substring(0,2), "");
			for(var j in regionMap[i][2]){
				if(rstr.substring(0,2) === (regionMap[i][2][j][0]).substring(0, 2)){
					regionArr[2] = j;
					regionArr[3] = regionMap[i][2][j][0];
					rstr = rstr.replace(regionMap[i][2][j][0], "");
					for(var k in regionMap[i][2][j][2]){
						if(regionMap[i][2][j][2][k][0] === rstr){
							regionArr[4] = k;
							regionArr[5] = rstr;
							regionArr[6] = true;
							regionArr[7] = k;
							return regionArr;
						}
					}
				}
			}
		}
	}
	return regionArr;
};

function $regionGetStr(rid){
	//根据地址id来取地址的描述字符串，如果是直辖市则不写省名称
	var regionMap=$getRegionMap();
	if(rid==""){
		return "";
	}
	var path=$regionGetPath(rid);
	//如果省的类别标记为1，则不加省后缀,表示是不需要加省描述的省，如新疆
	var pStr=(path[1])?path[1]+((regionMap[path[0]][1]==1)?"":"省"):"";
	var cStr=(path[3])?path[3]:"";
	//选中了市的话，判断是否直辖市，如果是的话就不显示省
	if(path[2]){
		if(regionMap[path[0]][2][path[2]][1]==1){
			pStr="";
		}
		//如果省的类别标记为2的话，标识不显示省名称，类似于直辖市的处理，如海外
		if((regionMap[path[0]][1]==2)){
			pStr="";
		}
	}
	var aStr=(path[5])?path[5]:"";
	return pStr+cStr+aStr;
};

function $wordRestrict(words,len,cnStrict,flag){
	//进行字符长度验证，如果超过长度则返回截断后的字符串
	if(cnStrict){
		var totleWords = words.replace(/[\u00FF-\uFFFF]/g, "  ").length;
		if(totleWords > len){
			var enw=words.replace(/[\u00FF-\uFFFF]/g, "@-").substr(0,len);
			var sublen=enw.match(/@-/g)?enw.match(/@-/g).length:0;
                        var flag=flag||"";
			return words.substring(0,  len-sublen)+flag;
		}
		return words;
	}else{
		return words.length>len?words.substring(0,len):words;
	}
}

function $stringSplitByLength(str,l,cuter){
	//按照指定字节数把字符串分行,参数:字符串，切割长度（单位字节），用来分隔的代码
	if(str.length<=l){return str}
	cuter=cuter?cuter:"<br/>"
	var returnVar=[];
	var cutString="";
	var start=0;
	for(var i=0;i<str.length;i++){
		cutString=str.substr(start,i-start);
		if(cutString.replace(/[\u00FF-\uFFFF]/g,"  ").length>=l){
			returnVar.push(cutString)
			cutString="";
			start=i;
		}
	}
	(cutString)?returnVar.push(cutString):"";
	return returnVar.join(cuter);
}

function $saveUrl(name,url){
	var name=name||document.title;
	var url	=url ||window.location.href;
	if (document.all){
		window.external.addFavorite(url,name);
	}else if(window.sidebar){
		window.sidebar.addPanel(name,url,"");
	};
	return false;
};

function $copyUrl(url){
	var url=url||window.location.href;
	try{
		window.clipboardData.setData('Text',url);
		alert("复制成功,请粘贴发给好友!");
	}catch(e){
		alert("您的浏览器不支持此功能，请直接复制网页地址!");
	}
};

function $isBrowser(str){
	str=str.toLowerCase();
	var b=navigator.userAgent.toLowerCase();
	var arrB=[];
	arrB['firefox']=b.indexOf("firefox")!=-1;
	arrB['opera']=b.indexOf("opera")!=-1;
	arrB['safari']=b.indexOf("safari")!=-1;
	arrB['gecko']=!arrB['opera']&&!arrB['safari']&&b.indexOf("gecko")>-1;
	arrB['ie']=!arrB['opera']&&b.indexOf("msie")!=-1;
	arrB['ie6']=!arrB['opera']&&b.indexOf("msie 6")!=-1;
	arrB['ie7']=!arrB['opera']&&b.indexOf("msie 7")!=-1;
	return arrB[str];
};

function $tabChange(cid,cs,ev,n,lazy){
//容器id，当前tab头的样式名，事件(click, mouseover...), 第一次显示第几个tab，是否切换到某个tab之后再load那个tab内容里的图片(1加载，其余不加载，需在图片中处理src和rel属性)
	if(!$$("#"+cid)||n<1) return;

	var tabw = $$("#" + cid + " .tabcon"),
		tabh = $$("#" + cid + " .tabnav li"),
		tabhLen = tabh.length,
		toId = n <= tabhLen ? n-1 : tabhLen-1;
	for (var i=0;i<tabhLen;i++){ $$(tabh[i]).attr("rel",i);	}

	tabh.eq(toId).addClass(cs);
	tabw.hide().eq(toId).show();
	if(lazy===1){loadImg(n); }

	tabh.bind(ev,function(){
		var tId = $$(this).attr("rel");
		if(lazy===1){ loadImg(tId); }
		$$(tabh[toId]).removeClass(cs);
		$$(tabw[toId]).hide();
		$$(tabh[tId]).addClass(cs);
		$$(tabw[tId]).show();
		toId = tId;
	});

	function loadImg(c){
		$$(tabw[c]).find("img").each(function(){
			if($$(this).attr("src")=="") {
				$$(this).attr("src",$$(this).attr("rel")); 
				$$(this).css("background-image","none"); 
			}
		});
	}

}

function $displayShow(ids){
	$display(ids,'');
};

function $animateFloat(obj){
	//设置一个动画移动的浮层，可展开，可收起（从指定大小，坐标变化为指定大小、坐标，执行完后自动关闭）
	var option={
		startY:0,
		startX:0,
		startH:0,
		startW:0,
		endY:0,
		endX:0,
		endH:0,
		endW:0,
		speed:400,
		callBack:function(){return true;}
	}
	for(var i in obj){
		option[i]=obj[i];
	}
	if(!window._animateFloatHandle){
		var d=document.createElement("div");
		d.id="animateDiv";
		d.style.position="absolute";
		d.style.zIndex=500;
		d.style.background="#ffffff";
		d.style.border="1px solid #666666";
		document.body.appendChild(d);
		window._animateFloatHandle=document.getElementById("animateDiv");
	}
	var d=_animateFloatHandle;
	d.style.height=option.startH+"px";
	d.style.width=option.startW+"px";
	d.style.top=option.startY+"px";
	d.style.left=option.startX+"px";
	$$(d).show();
	$$(d).animate(
		{
			"left":option.endX+"px",
			"top":option.endY+"px",
			"height":option.endH+"px",
			"width":option.endW+"px"
		},
		option.speed,"",
		function(){
			$$(this).hide();
			return option.callBack();
		}
	);
}

function $getAbsoluteTop(dom){
//取dom对象与页面顶部的绝对偏移
	if(!dom){return null;}
	var offsetTop=dom.offsetTop;
	while(dom=dom.offsetParent){
		offsetTop+=dom.offsetTop;
	}
	return offsetTop;
}

function $loadImagesByScroll(offsetH){
	//根据页面滚动状态按需请求需要的图片
	//初始化要加载的内容
	var bodyCache=document.body,
		domCache=(document.compatMode=='BackCompat')?bodyCache:document.documentElement,
		offsetH=(window.MessageEvent&&!$isBrowser('firefox'))?bodyCache.scrollTop:domCache.scrollTop,
		allImage=document.images,
		loadList={}//要加载的图片列表;//可见范围

	//遍历出需要按需加载的图片
	for(var i=0,len=allImage.length;i<len;i++){
		var oImg=allImage[i];
		if((typeof(oImg)=="object") && oImg.getAttribute("init_src") ){
			var _index=$getYP(oImg);
			_index=_index>offsetH?(_index-offsetH):0;
			(loadList[_index])?loadList[_index].push(oImg):loadList[_index]=[oImg];
		}
	}

	for(var i in loadList){
		$scroll({height:i,data:loadList[i],func:loadImg});
	}
	
	function loadImg(opt){
		for(var i=0,len=opt.data.length;i<len;i++){
			var oImg=opt.data[i];
			var src=oImg.getAttribute("init_src");
			if(src){
				oImg.setAttribute("src",src);
				oImg.removeAttribute("init_src");
			}
		}
	}
}

function $execFuncByScroll(obj){
//根据页面滚动状态按需执行js函数
	//初始化要加载的内容
	if(!window._scriptExecMap){
		window._scriptExecMap={
			dCount:0,
			body_cache:document.body,
			doe_cache:document.compatMode=='BackCompat'?body_cache:document.documentElement,
			funcList:[]
		};
	}
	if(obj){
		var _o=window._scriptExecMap;
		(_o.funcList[obj.height])?_o.funcList[obj.height].push(obj.func):_o.funcList[obj.height]=[obj.func];
		_o.dCount++;
	}
	
	var _o=window._scriptExecMap;
	//判断是否需要继续监控	获取当前页面滚动的距离  可见高度+已经滚动的高度
	if(_o.dCount<1){return;}
	var offsetH=(window.MessageEvent&&!navigator.userAgent.toLowerCase().indexOf('firefox')==-1)?_o.body_cache.scrollTop:_o.doe_cache.scrollTop;//已经滚动的高度
	var visioH=offsetH+_o.doe_cache.clientHeight;
	for(var i in _o.funcList){
		if(visioH>i){
			for(var l=0;l<_o.funcList[i].length;l++){
                   	   setTimeout(_o.funcList[i][l],0);

			}
			delete _o.funcList[i];
			_o.dCount--;
		}
	}
	setTimeout($execFuncByScroll,100);
}

function $strSubGB(str,start,len,flag){
    //进行字符长度验证，如果超过长度则返回截断后的字符串
    var total = $strLenGB(str);
    if(total > (len-start)){
        var flag=flag||"";
        var strTemp=str.replace(/[\u00FF-\uFFFF]/g, "@-").substr(start,len);
        var subLen =strTemp.match(/@-/g)?strTemp.match(/@-/g).length:0;        
        return str.substring(0,len-subLen)+flag;
    }
    return str;
}

function $arraySelect(arr, iterator){
    var res = []; 
    $$.each(arr, function(index, value){
        if (iterator(value, index)){
	    res.push(value);
	}
    }); 
    return res; 
}

function $addClass(ids,cName){
	$setClass(ids,cName,"add");	
};

function $delClass(ids,cName){	
	$setClass(ids,cName,"remove");
};

function $getCookie(name){
//读取COOKIE
	var reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)"),
		val=document.cookie.match(reg);//如果获取不到会提示null
	return val?unescape(val[2]):null;
};

function $getUin(){
	//返回当前登陆用户的QQ号码 ,没有则返回""
	var uin=$getCookie("uin");
	return uin?uin.replace("o0",""):"";
};

function $getNick(){
	//获取COOKIES中保存的用户昵称 
	var nick=$getCookie("hs");
	return nick?nick.replace(/[0,1]\/\d+\/[0,1]\//,""):'';
};

function $isLogin(){
	return ($getCookie("skey") && $getCookie("uin"))?true:false;
};

function $arrayEach(arr,func){
    return $$.each(arr,func);
}

function $getGradeName(opt){
	var option={
		score:0,
		type:"buyer",
		buyer:{
			gradeList:[0,1,5,11,21,41,101,201,501,1001,2001,5001,10001,30001,50001,80001,100001,150001,200001,250001,300001],
			gradeName:["","一星买家","二星买家","三星买家","四星买家","五星买家","一钻买家","二钻买家","三钻买家","四钻买家","五钻买家","一银冠买家","二银冠买家","三银冠买家","四银冠买家","五银冠买家","一金冠买家","二金冠买家","三金冠买家","四金冠买家","五金冠卖家"]
		},
		seller:{
			gradeList:[0,1,5,11,21,41,101,301,1001,3001,5001,10001,20001,50001,100001,200001,500001,1000001,2000001,5000001,10000001,1900000000,1901000000,1902000000],
			gradeName:["","一星卖家","二星卖家","三星卖家","四星卖家","五星卖家","一钻卖家","二钻卖家","三钻卖家","四钻卖家","五钻卖家","一银冠卖家","二银冠卖家","三银冠卖家","四银冠卖家","五银冠卖家","一金冠卖家","二金冠卖家","三金冠卖家","四金冠卖家","五金冠卖家","","",""]
		}
	};
	
	for(var i in opt){
		option[i]=opt[i];
	}
	
	//如果用户类型不对也什么不做  ,如果积分为空则什么也不做
	if(option.score.toString()=="" || !option[option.type]){
		return "";	
	}
	
	//参考信用的地方可能会出现字符串的情况
	if(option.type=="frefer" && option.score!="" && !parseInt(option.score)){	//不为空并且不是数字的话就原样返回
		option.score=option.score.replace(/[^\d]/g,"");
		if(option.score==""){
			return option.score;
		}
	}
	
	var _grade=0;
	var _range=option[option.type].gradeList;
	for(var i=0;i<_range.length;i++){
		//溢出最大范围时等级为最大
		if(option.score>=_range[_range.length-1]){
			_grade=_range.length-1;
			break;
		}
		//范围内的等级处理
		if(option.score>=_range[i] && option.score<_range[i+1]){
			_grade=i;
			break;
		}
	}
	return option[option.type].gradeName[_grade];
};

function $isMail(v){
	return /^([a-zA-Z0-9]+[_|\-|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\-|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]+$/.test(v)
};

function $setClass(ids,cName,kind){	
	if(typeof(ids)=="string"){
		var arrDom=ids.split(",");
		for(var i=0,len=arrDom.length;i<len;i++){
			setClass($id(arrDom[i]),cName,kind);
		}
	}else{
		setClass(ids,cName,kind);
	};
	
	function setClass(obj,cName,kind){
		var oldName=obj.className,
			arrName=oldName?oldName.split(' '):[];
		if(kind=="add"){
			if(!$hasClass(oldName,cName)){
				arrName.push(cName);
				obj.className=arrName.join(' ');
			}
		}else if(kind=="remove"){
			var newName=[];
			for(var i=0,len=arrName.length;i<len;i++){
				if(cName!=arrName[i]&&' '!=arrName[i]){
					newName.push(arrName[i]);
				}
			};
			obj.className=newName.join(' ');
		}
	}	
};

(function(){
	var _formatJson_cache = {};
	
	$formatJson=function(str, data){
   	 	/* 模板替换,str:模板id或者内容，data:数据内容
			\W：匹配任何非单词字符。等价于 '[^A-Za-z0-9_]'。 
			如果是id,并且cache中有值，直接返回，否则获取innerHTML，再次解析；
			如果不是id，解析并存入cache
		 */
		var fn = !/\W/.test(str)?
			_formatJson_cache[str]=_formatJson_cache[str] || $formatJson($id(str).innerHTML) :
				new Function("obj",
					"var p=[],print=function(){p.push.apply(p,arguments);};" +
					"with(obj){p.push('" +str
					.replace(/[\r\t\n]/g, " ")
					.split("<%").join("\t")
					.replace(/((^|%>)[^\t]*)'/g, "$1\r")
					.replace(/\t=(.*?)%>/g, "',$1,'")
					.split("\t").join("');")
					.split("%>").join("p.push('")
					.split("\r").join("\\'") + "');}return p.join('');");
		return data ? fn( data ) : fn;
	}
})();

function $postToWb(o){
	
	var opt = {
		title: encodeURIComponent(o.title),
		url: encodeURIComponent(o.url),
		appkey: encodeURI(o.appkey),//你从腾讯获得的appkey
		pic: encodeURIComponent(o.pic),//（例如：var _pic='图片url1|图片url2|图片url3....）
		site: encodeURIComponent(o.site)//你的网站地址
	};
	
	var query = [];
	for(var i in opt){
		query.push(i+"="+opt[i]);
	}
	
	var url = 'http://v.t.qq.com/share/share.php?'+query.join('&');
	window.open( url,'wb', 'width=700, height=680, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, location=yes, resizable=no, status=no' );
};

function $getTarget(e,parent,tag) {
	var	e=window.event||e,
		tar=e.srcElement||e.target;
	if(parent && tag && tar.nodeName.toLowerCase()!=tag){
		while(tar = tar.parentNode){
			//对下拉框的点击会回溯到document，其它最多回溯到document.body即可
			if(tar==parent || tar==document.body || tar==document){
				return null;
			}else if(tar.nodeName.toLowerCase()==tag){
				break;
			}
		}
	};
	return tar;
}

function $makeUrl(data){
	//将json串组装成为url并返回
	var arr=[];
	for( var k in data) {
		arr.push(k+"="+data[k]);
	};
	return arr.join("&");
};

function $strTrimLeft(str,code){
	code = code||"\\s";
	return str.replace(new RegExp("(^"+ code + "*)","g"),""); 
}

function $strTrimRight(str,code){
	code = code||"\\s";
	return str.replace(new RegExp("(" + code + "*$)","g"),""); 
}

function $md5(){
	// md5加密
	var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
	var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */
	var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */
	var option={};
	option.hexcase=hexcase;
	option.b64pad=b64pad;
	option.chrsz=chrsz;
	option.hex_md5=hex_md5;
	option.binl2hex=binl2hex;
	option.core_md5=core_md5;
	
	return option;
	function hex_md5(s){ 
		return binl2hex(core_md5(str2binl(s), s.length * option.chrsz));
	}
	function binl2hex(binarray){
		var hex_tab = option.hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
		var str = "";
		for(var i = 0; i < binarray.length * 4; i++)
		{
		  str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
				 hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
		}
		return str;
	}
	function core_md5(x, len){
		/* append padding */
		x[len >> 5] |= 0x80 << ((len) % 32);
		x[(((len + 64) >>> 9) << 4) + 14] = len;
		
		var a =  1732584193;
		var b = -271733879;
		var c = -1732584194;
		var d =  271733878;
		
		for(var i = 0; i < x.length; i += 16){
			var olda = a;
			var oldb = b;
			var oldc = c;
			var oldd = d;
		  
			a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
			d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
			c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
			b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
			a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
			d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
			c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
			b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
			a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
			d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
			c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
			b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
			a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
			d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
			c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
			b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);
		  
			a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
			d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
			c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
			b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
			a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
			d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
			c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
			b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
			a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
			d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
			c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
			b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
			a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
			d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
			c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
			b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
		  
			a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
			d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
			c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
			b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
			a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
			d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
			c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
			b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
			a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
			d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
			c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
			b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
			a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
			d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
			c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
			b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
		  
			a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
			d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
			c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
			b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
			a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
			d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
			c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
			b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
			a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
			d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
			c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
			b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
			a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
			d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
			c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
			b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
		  
			a = safe_add(a, olda);
			b = safe_add(b, oldb);
			c = safe_add(c, oldc);
			d = safe_add(d, oldd);
		}
		return Array(a, b, c, d);
	}

	function md5_cmn(q, a, b, x, s, t){
		return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
	}
	function md5_ff(a, b, c, d, x, s, t){
		return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
	}
	function md5_gg(a, b, c, d, x, s, t){
		return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
	}
	function md5_hh(a, b, c, d, x, s, t){
		return md5_cmn(b ^ c ^ d, a, b, x, s, t);
	}
	function md5_ii(a, b, c, d, x, s, t){
		return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
	}

	function safe_add(x, y){
		var lsw = (x & 0xFFFF) + (y & 0xFFFF);
		var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
		return (msw << 16) | (lsw & 0xFFFF);
	}
	function bit_rol(num, cnt){
		return (num << cnt) | (num >>> (32 - cnt));
	}

	function str2binl(str){
		var bin = Array();
		var mask = (1 << option.chrsz) - 1;
		for(var i = 0; i < str.length * option.chrsz; i += option.chrsz)
		  bin[i>>5] |= (str.charCodeAt(i / option.chrsz) & mask) << (i%32);
		return bin;
	}
}

function $focusInput(id,note){
	var o=$id(id);
	$addEvent(o,'focus',function(){
		o.style.color='#000000';
		if(note&&note!=''&&o.value==note){
			o.value='';
		}		
	});
	$addEvent(o,'blur',function(){
		if(note&&o.value==''){
			o.value=note;
			o.style.color='#999999';
		}	
	});	
};

function $addSelect(e,t,v){		
	//新增一个下拉框
	var o = new Option(t, v);
	e.options[e.options.length]=o;
	return o;
};

function $delEvent(obj,type,handle){
	if (window.removeEventListener){
		obj.removeEventListener(type, handle, false);
	}else if (window.detachEvent){
		obj.detachEvent("on"+type, handle);
	}
};

function $bindEvent(name,type,handle){
	//专用于批量绑定名字相同的事件,单独绑定直接写onclick等
	var objs=document.getElementsByName(name);
	for(var i=0,len=objs.length;i<len;i++){
		$addEvent(objs[i],type,handle);
	}
};

function $isPInt(v){
	//正整数
	return /^[1-9]\d*$/.test(v); 
};

function $isQQ(v){
	return /^[1-9]\d{4,9}$/.test(v); 
};

function $getValue(name){
	//专门用于check和radio取值，单独取值请直接写value
	var objs=document.getElementsByName(name),
		returnvar=[];
	for(var i=0,len=objs.length;i<len;i++){
		var t=objs[i];
		if(t.tagName.toLowerCase()=="input"){
			if((t.type.toLowerCase()=="checkbox" || t.type.toLowerCase()=="radio") ){	//设置单选复选框的值
				if(t.checked==true){
					returnvar.push(t.value);
				}
			}
		}
	};
	returnvar=returnvar.join(',');
	return returnvar;
};

function $doClick(id){
	var o = $id(id);        
	if($isBrowser('ie')){o.click()}        
	else{        
		var	e = document.createEvent('MouseEvents');        
		e.initEvent('click',true,true);        
		o.dispatchEvent(e);        
	}  
};

function $getSalePrice(sale,price){
//获取商品折扣价格，参数：折扣率（0.50），总价（单位元）
	if(sale>=1.0){
		return parseFloat(price).toFixed(2);
	}
	var memberprice=price*sale;
	if(price<=50){
		memberprice+=0.05; 
		memberprice=parseInt(memberprice*100/10)/10;
	}else{
		memberprice+=0.5;
		memberprice=parseInt(memberprice);
	}
	if(memberprice<=0.01){
		memberprice=0.01;
	}
	return parseFloat(memberprice).toFixed(2);
}

function $getTextLengthByByte(txt){
   if(txt==null){
	  return 0;  
   }
   var asc; 
   var txtLen=0; 
   for(var i=0;i<txt.length;i++)
   {
	  asc=txt.charCodeAt(i);  
	  if(asc>0&&asc<255){
	   txtLen+=1;   
	  }else{
	   txtLen+=2;   
	  }
   }
   return txtLen; 
}

function $getTextByByteLength(txt,getLen){

//根据字节长度截取字符串
//txt:文本
//getLen:字节长度
	 if(txt==null){
		 return "";
	 }
	 var asc;
	 //ASCII码
	 var txtLen=$getTextLengthByByte(txt);
	 //txt的实际长度
	 var txtNew="";
	 //获取新的字符串
	 var tempLen=0;
	 //临时变量
	 var txtTemp="";
	 //临时变量
   
	if(txtLen>getLen)//如果txt字符串的长度大于要截取的
	{  
	  for(var i=0;i<txt.length;i++){  
		   asc=txt.charCodeAt(i);   
		   if(asc>0&&asc<255){
			tempLen+=1;      
		   }else {
			tempLen+=2;    
		   }
		   if(tempLen>getLen){
			txtNew=txtTemp;
			//提取当前长度
		   }else {
			txtTemp+=txt.substr(i,1);
		   }
	  }
	}else {
	  txtNew=txt;
	}
    return txtNew; 
	 
}

function $getTimeInterval(st,et){
	//返回两个时间之间的间隔的描述字符串
   var dateLeft = 0;
    var hourLeft = 0;
    var minuteLeft = 0;
    var secondLeft = 0;
	var timeLeft=[0,0,0,0];//结构：天、小时、分、秒
	var timeStr="";
	var ts=(et>st)?parseInt((et-st)/1000):0;
	timeLeft[0]=(ts>86400)?parseInt(ts/86400):0;
	ts=ts - timeLeft[0] * 86400;
	timeLeft[1]=(ts>3600)?parseInt(ts/3600):0;
	ts=ts - timeLeft[1] * 3600;
	timeLeft[2]=(ts>60)?parseInt(ts/60):0;
	timeLeft[3]=ts - timeLeft[2] * 60;
	timeStr=(timeLeft[0]>0)?timeLeft[0]+"天":"";
	timeStr+=(timeLeft[0]<=0 && timeLeft[1]<=0)?"":(timeLeft[1]+"小时");
	timeStr+=(timeLeft[0]<=0 && timeLeft[1]<=0 && timeLeft[2]<=0)?"":(timeLeft[2]+"分钟");
	timeStr+=(timeLeft[0]<=0 && timeLeft[1]<=0 && timeLeft[2]<=0 && timeLeft[3]<=0)?"":timeLeft[3]+"秒";
	return timeStr;
}

function $timeCountDown(obj){
	//商品倒计时器，参数：输出时间字符串的dom，开始时间（单位毫秒）,结束时间,当前状态（默认为2才会计算）
	var option={
		dom:"",
		endTime:(new Date()).getTime(),
		startTime:(new Date()).getTime(),
		state:2		//默认在售
	};
	for(var i in obj){
		option[i]=obj[i];
	}
	switch(parseInt(option.state)){
		case 2:
			var str=$getTimeInterval(option.startTime,option.endTime);
			if(str){
				option.startTime+=1000;
				setTimeout(function(){$timeCountDown(option);},1000);
			}else{
				var str="成交结束";
			}
			break;
		case 4:
			var str="即将开始";
			break;
		default:
			var str="成交结束";
			break
	}
	option.dom.innerHTML=str;
}

function $scroller(opt){
	//滚动器定义的代码
	var option={
		framer:"",		//滚动区的框架 div的id，框架内的内容就是要被滚动的区域，框架本身不滚动
		height:20,		//滚动区域的高度
		width:100,		//滚动区域的宽度
		viewtime:2000,		//每一屏停止时的展示时间,单位毫秒
		speed:40,		//滚动的速度，每次移动一个像素的等待时间。单位毫秒
		scrollHeight:0,	//每次滚屏的高度，如果不设置则等于滚动区域高度，即默认1屏1屏的滚动
		mouseControl:true,//鼠标控制开关，为true的时候，onmouserover的时候会增加停止开关,onmouserout的时候又会打开，这个状态控制的是stopScroll属性
		currentTop:0,	//代码中的状态机：已经滚动了多少？
		stopTime:0,		//代码中的状态机：处于停止状态时的计数器
		stopScroll:0	//代码中的状态机：是否停止状态
	};
	//合并参数
	$$.extend(option,opt);
	//获取外部框架的句柄，如果不存在就什么也不做
	option.div=$$("#"+option.framer);
	if(option.div.length<1){
		return;
	}
	//如果滚屏高度为0的时候就让他等于默认一屏的高度
	if(option.scrollHeight==0){
		option.scrollHeight=option.height;
	}
	//把框架内的内容复制几份，为连续滚动做准备,并设置框架的有效高度和宽度
	option.div.append(option.div.html()).append(option.div.html()).append(option.div.html()).append(option.div.html()).css("height",option.height+"px").css("width",option.width+"px").css("overflow","hidden").css("display","block").get(0).scrollTop=0;
	//绑定鼠标事件，鼠标在上面的时候把停止标记上打1
	if(option.mouseControl){
		option.div.mouseover(function(){
			option.stopScroll=1;;
		}).mouseout(function(){
			option.stopScroll=0;
		});
	}
	//每个单位时间启动一次滚动
	doScroll.runEach(option.speed,option);
	//辅助函数：执行一次滚动操作
	function doScroll(opt){
		if(opt.stopScroll==1) return;		//判断是否返回
		opt.currentTop +=1 ;			//滚动高度+1
		if(opt.currentTop == opt.scrollHeight+1){//这个时候应该是刚好滚动了一轮，就应该开始停止一段时间了
			opt.stopTime+=1;//停止的时间开始计数
			opt.currentTop -=1 ;	//倒退一个像素，让他始终停在同一个位置
			if(opt.stopTime*opt.speed >= opt.viewtime){//已经停止了指定的时间长度
				opt.currentTop=0;	//把滚动高度设置为0，就可以继续滚动了
				opt.stopTime=0;	//停止时间设置为0
			}
		}else{//这一块是符合向上滚动条件的时候逻辑，向上滚动一像素
			var preTop = opt.div.get(0).scrollTop;		//已经滚动的高度
			option.div.get(0).scrollTop += 1;//真正在视觉上像上滚动一个像素，如果已经到了底部的话这次滚动无效，数值不会变
			if(preTop==opt.div.get(0).scrollTop){//滚到底部则需要重新跳到头部去。
				opt.div.get(0).scrollTop=0; 
				opt.currentTop=0;
			}
		}
	}
};

function $getQQNum(){
         var QQNum=$getCookie("uin");
	if(QQNum){
		return QQNum.replace("o0","");
	}else{
		return "";
	};
}

function $addHover(obj){
//标签后的箭头加上hover弹出下拉框效果
	var option = {
		outLiID:"",
		downListID:"",
		hoverSpanID:""
	}
	for(var i in obj){
		option[i] = obj[i];
	}
	var	oHover=$id(option.outLiID),
		oList=$id(option.downListID),
		oBind=option.hoverSpanID===""?oHover:$id(option.hoverSpanID);
	$mouseover(oBind,function(){
		oList.className = "now";
	});
	$mouseout(oHover,function(){
		oList.className = "now h";
	});
};

function $isMobile(v){
/*
　　中国移动号段 1340-1348 135 136 137 138 139 150 151 152 157 158 159 187 188 147 182
　　中国联通号段 130 131 132 155 156 185 186 145
　　中国电信号段 133 1349 153 180 189
*/	
	var cm="134,135,136,137,138,139,150,151,152,157,158,159,187,188,147,182",
		cu="130,131,132,155,156,185,186,145",
		ct="133,153,180,189",
		h1=v.substring(0,3),
		h2=v.substring(0,4),
		v=(/^1\d{10}$/).test(v)?(cu.indexOf(h1)>=0?"联通":(ct.indexOf(h1)>=0?"电信":(h2=="1349"?"电信":(cm.indexOf(h1)>=0?"移动":"未知")))):false;
	//首先找是否联通，然后查找是否电信，然后在移动中查找‘1349’为电信，最后在移动中查找
	return v; 
};

function $cutdownFloat(opt) {
    var option = {
        time: 0,
        title: "提示",
        html: "",
        left: "",
        top: "",
        width: '300',
        height: "",
        fix: false, //是否固定居中随屏幕滚动，如果为true则left和top无效
        style: "stand", //stand\none\poptip
        cover: false, //显示覆盖背景
        leaver: 2,
        showTime: false
    };
    option = $extend(option, opt);
    option.onClose = function () { clearInterval(window.cutdownInterval); return true; }  //关闭事件
    var autoClose = parseInt(option.time) == 0 ? false : true;
    option.html = '<table style="width:100%;height:100%"><tr><td style="vertical-align:top;width:32px;"><span class="msg3-icon-info"></span></td><td>' + option.html + '</td></tr><tr><td style="text-align:center;" colspan=2><br /><p><button id="__btn__ok">确　定</button><span id="__seconds__" style="margin-left:10px;display:none;">' + (autoClose ? parseInt(option.time) / 1000 : '') + '</span></p></td></tr></table>';
    var alertFloat = $float(option);
    if (option.showTime) {
        $$("#__seconds__").show();
    }
    if (autoClose) {
        window.cutdownInterval = setInterval(function () {
            var time = parseInt(option.time);
            if (time > 1000) {
                option.time -= 1000;
                $$("#__seconds__").html(time / 1000 - 1);
            } else {
                alertFloat.close();
            }
        }, 1000);
    }
    $$("#__btn__ok").click(function () {
        alertFloat.close();
    });
};

function $mouseScroller(opt){
  //鼠标拖动元素组件
  var option={
	  scrollerMin:0,			//有效范围
	  scrollerMax:100,
	  percent:0,				//postion在min，max的百分比
	  delta:0,				//position与min的偏差
	  scrollerPosition:0,		//最后有效的位置值
	  scrollerDrag:false,		//是否启用
	  scrollerRangeExtend:true,		//当超出范围时，是否当做极值并发送scroll事件
	  scrollType:"x",			//方向，支持"x"，"y"
	  onStart:function(obj){
	  },							//初始化完成，随时可以触发
	  onScroll:function(obj){
	  },
	  onInit:function(obj){
	  },						//触发开始，初始化document事件
	  onComplete:function(obj){
	  },
	  startScroll:function(){
	  }	//外部逻辑判断是否开始监听滚动，调用此函数
  };
  option.startScroll=goScroll;
  //合并参数
  for(var i in opt){
	  option[i]=opt[i];
  }
  return option;
  function goScroll(){
	  if(option.onInit)option.onInit(option);
	  document.onmousemove=function(e){
		  var evt=e||window.event;
		  if(!evt||!option.scrollerDrag)return false;
		  var mousex=evt.clientX;
		  var mousey=evt.clientY;
		  var position=0;
		  switch(option.scrollType){
			  case "x":
			  position=mousex;
			  break;
			  case "y":
			  position=mousey;
			  break;
		  }
		  if(position>=option.scrollerMin&&position<=option.scrollerMax){
			  option.scrollerPosition=position;
			  option.delta=option.scrollerPosition-option.scrollerMin;
			  option.percent=option.delta/(option.scrollerMax-option.scrollerMin);
			  if(option.onScroll)option.onScroll(option);
		  }else if(position<option.scrollerMin && option.scrollerRangeExtend){
			  option.scrollerPosition=option.scrollerMin;
			  option.delta=0;
			  option.percent=0;
			  if(option.onScroll)option.onScroll(option);
		  }else if(position>option.scrollerMax && option.scrollerRangeExtend){
			  option.scrollerPosition=option.scrollerMax;
			  option.delta=option.scrollerPosition-option.scrollerMin;
			  option.percent=1;
			  if(option.onScroll)option.onScroll(option);
		  }
		  return false;
	  }
	  document.onmouseup=function(){
		  if(option.scrollerDrag){
			  option.scrollerDrag=false;
			  document.onmousemove=null;
			  if(option.onComplete)option.onComplete(option);
		  }
	  }
	  option.scrollerDrag=true;
	  if(option.onStart)option.onStart(option);
  }
}

function $getKeyCode(e) {
	var	e=e||window.event;
	return	e.keyCode||e.which;
}

//获取0-N之间的随机整数
function $randomInt(num){
	return Math.floor(Math.random()*num);
};

function $json2temp( json, temp ){
	for( var i in json )
	{
		var reStr = i;
		var re = new RegExp( "{#"+reStr+"#}", "gi" );
		temp = temp.replace( re, json[i] )	;	
	}
	return temp;
};

function $checkIdcard(idcard){
  //var Errors=new Array("验证通过!","身份证号码位数不对!","身份证号码出生日期超出范围或含有非法字符!","身份证号码校验错误!","身份证地区非法!");
  var Errors=[true, "身份证号码位数不对!","身份证号码出生日期超出范围或含有非法字符!","身份证号码校验错误!","身份证地区非法!"];
  var area={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"}
  var idcard,Y,JYM;
  var S,M;
  var idcard_array = new Array();
  idcard_array = idcard.split("");
  if(area[parseInt(idcard.substr(0,2))]==null) return Errors[4];
  switch(idcard.length){
    case 15:
      if ((parseInt(idcard.substr(6,2))+1900) % 4 == 0 || ((parseInt(idcard.substr(6,2))+1900) % 100 == 0 && (parseInt(idcard.substr(6,2))+1900) % 4 == 0 )){
        ereg = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$/;//测试出生日期的合法性
      }
      else{
        ereg = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$/;//测试出生日期的合法性
      }
      if(ereg.test(idcard))
        return Errors[0];
      else
        return Errors[2];
    break;
  case 18:
    if ( parseInt(idcard.substr(6,4)) % 4 == 0 || (parseInt(idcard.substr(6,4)) % 100 == 0 && parseInt(idcard.substr(6,4))%4 == 0 )){
      ereg = /^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$/;//闰年出生日期的合法性正则表达式
    }
    else{
    ereg = /^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$/;//平年出生日期的合法性正则表达式
    }
    if(ereg.test(idcard)){
      S = (parseInt(idcard_array[0]) + parseInt(idcard_array[10])) * 7 + (parseInt(idcard_array[1]) + parseInt(idcard_array[11])) * 9 + (parseInt(idcard_array[2]) + parseInt(idcard_array[12])) * 10 + (parseInt(idcard_array[3]) + parseInt(idcard_array[13])) * 5 + (parseInt(idcard_array[4]) + parseInt(idcard_array[14])) * 8 + (parseInt(idcard_array[5]) + parseInt(idcard_array[15])) * 4 + (parseInt(idcard_array[6]) + parseInt(idcard_array[16])) * 2 + parseInt(idcard_array[7]) * 1 + parseInt(idcard_array[8]) * 6 + parseInt(idcard_array[9]) * 3 ;
      Y = S % 11;
      M = "F";
      JYM = "10X98765432";
      M = JYM.substr(Y,1);
      if(M == idcard_array[17].toUpperCase())
        return Errors[0];
      else
        return Errors[3];
    }
    else
      return Errors[2];
    break;
  default:
    return Errors[1];
    break;
  }
}

function $tabExchange(obj){
    var opt={
        titleId:"",    //tab标题的id
        titleTag:"",    //tab的元素类型
        contentId:"",    //内容的id    
        contentTag:"",    //内容元素类型
		className:"current",
        initIndex:0,
        timeLag:0,
		func:$empty()
    };
	
    for(var i in obj){
        opt[i]=obj[i];
    }
    //遍历所有的标题tab，并绑定事件
    var oTitle=$id(opt.titleId),
		tabs=oTitle.childNodes,
		oContent=$id(opt.contentId),
    	contents=oContent.childNodes,
    	_cont=[],
		_tabs=[],
		_imgs=[],//图片是否已经载入
		conTentTag=opt.contentTag.toLowerCase(),
		titleTag=opt.titleTag.toLowerCase(),
		intr=null,
		tabLen=0;//实际长度
		
    for(var i=0,len=contents.length;i<len;i++){
		var oContent=contents[i];
        if(conTentTag==oContent.nodeName.toLowerCase()){
            _cont.push(oContent);
        }
    }
	
    for(var i=0,len=tabs.length;i<len;i++){
		var oTab=tabs[i];
        if(titleTag==oTab.nodeName.toLowerCase()){			
            _tabs.push(oTab);	
			
			//给Tab绑定mouseover
			oTab.onmouseover=(function(cur){
				return function(){
					if(cur!=opt.initIndex){
						intr=setTimeout(function(){
							if(!_imgs[cur]){
								//如果已经在如果就不要再载入了
								loadImg(_cont[cur]);
								_imgs[cur]=true;
							};
							_cont[opt.initIndex].style.display="none";
							_tabs[opt.initIndex].className="";
							_cont[cur].style.display="block";
							_tabs[cur].className=opt.className;	
							opt.initIndex=cur;	
							opt.func(cur);
						},opt.timeLag);		
					}
				}
			})(tabLen++);
					
			oTab.onmouseout = function(){
				clearTimeout(intr);
			};
        }
    }
	
    if(_tabs.length != _cont.length) return;
	
    //根据initIndex设置显示的tab页    
	for(var j=0,len=tabLen;j<len;j++){
		_cont[j].style.display=(j==opt.initIndex)?"block":"none";
	}
	
    //初始载入默认显示Tab
    if(_tabs[opt.initIndex]){
        _tabs[opt.initIndex].className = opt.className;   		
		loadImg(_cont[opt.initIndex]);
		_imgs[opt.initIndex]=true;
    }

	
	function loadImg(obj){
		var images = obj.getElementsByTagName("IMG");
		for(var i=0,len=images.length;i<len;i++){
			var oImg=images[i],
				oImgBack=oImg.getAttribute("back_src");
			if(''==oImg.src&&oImgBack){
				oImg.src = oImgBack;
			}
		}
	}
};

function $reSizeImg(obj, newW, newH){
//resize图片大小
	if(obj == null) return;
	var oImg = new Image();
	oImg.src = obj.src;
	var oldW = oImg.width;
	var oldH = oImg.height;
	if(oldW > newW || oldH > newH) {
		w = oldW/newW; 
		h = oldH/newH;
		if(h > w) w=h;
		oldW = oldW/w; 
		oldH = oldH/w;
	}
	if(oldW > 0 && oldH > 0){
		obj.width=oldW;
		obj.height=oldH;
	}
}

function $xmlHttpLoader(){
//创建xmlHttpRequest对象
	var cJ=null,i;
	if(window.fO){
		i=window.fO;
	}else{
		i=1;
	}
	do{
		try{
			switch(i){
				case 1:cJ=new ActiveXObject("Msxml2.XMLHTTP.4.0");
				break;
				case 2:cJ=new ActiveXObject("Msxml2.XMLHTTP");
				break;
				case 3:cJ=new ActiveXObject("Microsoft.XMLHTTP");
				break;
				case 4:cJ=new XMLHttpRequest();
				break;
				default:alert("很抱歉，您浏览器的ActiveX控件目前被设置为禁用，请修改浏览器的相关选项.");return null;
				break;
			}
		}catch(e){
		}
		if(cJ==null){
			i++;
		}else{
			window.fO=i;
			return cJ;
		}
	}
	while(true);
	return null;
}

function $getUserPic(qq,size){
	var html='<img src="http://qlogo'+(parseInt(qq)%4+1)+'.store.qq.com/qzone/'+qq+'/'+qq+'/'+size+'" alt="" />';
	return html;
};

function $autoLoadImages(){
	//卖场专用图片按需加载组件，图片把src改为init_src即可，可支持异步加载的数据
	window['_PP_core_autoLoadImages_data']={
		allNum:0,
		nosrcImages:[],
		nosrcLength:0, //无src的图片个数
		ciguid:0,		//临时分配的guid编号
		ptr:null //定时器句柄
	};
	window._PP_core_autoLoadImages_data.ptr = setInterval(function(){
		doScroll()		 
	},100);
	function doScroll(){
		var data=window['_PP_core_autoLoadImages_data'],
		allImage=document.images;
		//如果有iguid属性的图片则说明这个图片已经处理过了。
		if(allImage.length>data.allNum){
			for(var i=0,j=allImage.length;i<j;i++){
				if(!allImage[i].getAttribute("iguid")){
					allImage[i].setAttribute("iguid",data.ciguid++);
					var src=allImage[i].getAttribute("init_src")
					if(src){
						data.nosrcImages.push([allImage[i],src,$getY(allImage[i])]);
					}
				}
			}
			data.nosrcLength = data.nosrcImages.length;
			data.allNum=allImage.length;
		}
		//如果没有图片可加载的话
		if(data.nosrcLength==0){
			if(data.ptr){
				clearInterval(data.ptr);
				data.ptr = null;
				data.allNum = 0;
				data.nosrcImages = [];
			}	
			return;
		};
		
		var bodyCache=document.body,
			domCache=(document.compatMode=='BackCompat')?bodyCache:document.documentElement,
			offsetH=(window.MessageEvent&&!$isBrowser('firefox'))?bodyCache.scrollTop:domCache.scrollTop,
			visibleH=offsetH + domCache.clientHeight;//可见范围
		
		for(var i=0,j=data.nosrcImages.length;i<j;i++){
			if(!data.nosrcImages[i]){continue;}
			if((visibleH+100)>data.nosrcImages[i][2]){
				//无论是否需要，把传入进来的opt再传入调用函数
				var _item=data.nosrcImages[i];
				_item[0].setAttribute("src",_item[1]);
				delete data.nosrcImages[i];
				data.nosrcLength--;
			}
		}		
	}
};

function $find(selector, context, results, seed){
	/*!
 * Sizzle CSS Selector Engine - v1.0
 *  Copyright 2009, The Dojo Foundation
 *  Released under the MIT, BSD, and GPL Licenses.
 *  More information: http://sizzlejs.com/
 */
	var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
	done = 0,
	toString = Object.prototype.toString,
	hasDuplicate = false,
	baseHasDuplicate = true;

	// Here we check if the JavaScript engine is using some sort of
	// optimization where it does not always call our comparision
	// function. If that is the case, discard the hasDuplicate value.
	//   Thus far that includes Google Chrome.
	[0, 0].sort(function(){
		baseHasDuplicate = false;
		return 0;
	});

var Sizzle = function(selector, context, results, seed) {
	results = results || [];
	context = context || document;

	var origContext = context;

	if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
		return [];
	}
	
	if ( !selector || typeof selector !== "string" ) {
		return results;
	}

	var parts = [], m, set, checkSet, extra, prune = true, contextXML = Sizzle.isXML(context),
		soFar = selector, ret, cur, pop, i;
	
	// Reset the position of the chunker regexp (start from head)
	do {
		chunker.exec("");
		m = chunker.exec(soFar);

		if ( m ) {
			soFar = m[3];
		
			parts.push( m[1] );
		
			if ( m[2] ) {
				extra = m[3];
				break;
			}
		}
	} while ( m );

	if ( parts.length > 1 && origPOS.exec( selector ) ) {
		if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
			set = posProcess( parts[0] + parts[1], context );
		} else {
			set = Expr.relative[ parts[0] ] ?
				[ context ] :
				Sizzle( parts.shift(), context );

			while ( parts.length ) {
				selector = parts.shift();

				if ( Expr.relative[ selector ] ) {
					selector += parts.shift();
				}
				
				set = posProcess( selector, set );
			}
		}
	} else {
		// Take a shortcut and set the context if the root selector is an ID
		// (but not if it'll be faster if the inner selector is an ID)
		if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
				Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
			ret = Sizzle.find( parts.shift(), context, contextXML );
			context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0];
		}

		if ( context ) {
			ret = seed ?
				{ expr: parts.pop(), set: makeArray(seed) } :
				Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
			set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set;

			if ( parts.length > 0 ) {
				checkSet = makeArray(set);
			} else {
				prune = false;
			}

			while ( parts.length ) {
				cur = parts.pop();
				pop = cur;

				if ( !Expr.relative[ cur ] ) {
					cur = "";
				} else {
					pop = parts.pop();
				}

				if ( pop == null ) {
					pop = context;
				}

				Expr.relative[ cur ]( checkSet, pop, contextXML );
			}
		} else {
			checkSet = parts = [];
		}
	}

	if ( !checkSet ) {
		checkSet = set;
	}

	if ( !checkSet ) {
		Sizzle.error( cur || selector );
	}

	if ( toString.call(checkSet) === "[object Array]" ) {
		if ( !prune ) {
			results.push.apply( results, checkSet );
		} else if ( context && context.nodeType === 1 ) {
			for ( i = 0; checkSet[i] != null; i++ ) {
				if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
					results.push( set[i] );
				}
			}
		} else {
			for ( i = 0; checkSet[i] != null; i++ ) {
				if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
					results.push( set[i] );
				}
			}
		}
	} else {
		makeArray( checkSet, results );
	}

	if ( extra ) {
		Sizzle( extra, origContext, results, seed );
		Sizzle.uniqueSort( results );
	}

	return results;
};

Sizzle.uniqueSort = function(results){
	if ( sortOrder ) {
		hasDuplicate = baseHasDuplicate;
		results.sort(sortOrder);

		if ( hasDuplicate ) {
			for ( var i = 1; i < results.length; i++ ) {
				if ( results[i] === results[i-1] ) {
					results.splice(i--, 1);
				}
			}
		}
	}

	return results;
};

Sizzle.matches = function(expr, set){
	return Sizzle(expr, null, null, set);
};

Sizzle.find = function(expr, context, isXML){
	var set;

	if ( !expr ) {
		return [];
	}

	for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
		var type = Expr.order[i], match;
		
		if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
			var left = match[1];
			match.splice(1,1);

			if ( left.substr( left.length - 1 ) !== "\\" ) {
				match[1] = (match[1] || "").replace(/\\/g, "");
				set = Expr.find[ type ]( match, context, isXML );
				if ( set != null ) {
					expr = expr.replace( Expr.match[ type ], "" );
					break;
				}
			}
		}
	}

	if ( !set ) {
		set = context.getElementsByTagName("*");
	}

	return {set: set, expr: expr};
};

Sizzle.filter = function(expr, set, inplace, not){
	var old = expr, result = [], curLoop = set, match, anyFound,
		isXMLFilter = set && set[0] && Sizzle.isXML(set[0]);

	while ( expr && set.length ) {
		for ( var type in Expr.filter ) {
			if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
				var filter = Expr.filter[ type ], found, item, left = match[1];
				anyFound = false;

				match.splice(1,1);

				if ( left.substr( left.length - 1 ) === "\\" ) {
					continue;
				}

				if ( curLoop === result ) {
					result = [];
				}

				if ( Expr.preFilter[ type ] ) {
					match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );

					if ( !match ) {
						anyFound = found = true;
					} else if ( match === true ) {
						continue;
					}
				}

				if ( match ) {
					for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
						if ( item ) {
							found = filter( item, match, i, curLoop );
							var pass = not ^ !!found;

							if ( inplace && found != null ) {
								if ( pass ) {
									anyFound = true;
								} else {
									curLoop[i] = false;
								}
							} else if ( pass ) {
								result.push( item );
								anyFound = true;
							}
						}
					}
				}

				if ( found !== undefined ) {
					if ( !inplace ) {
						curLoop = result;
					}

					expr = expr.replace( Expr.match[ type ], "" );

					if ( !anyFound ) {
						return [];
					}

					break;
				}
			}
		}

		// Improper expression
		if ( expr === old ) {
			if ( anyFound == null ) {
				Sizzle.error( expr );
			} else {
				break;
			}
		}

		old = expr;
	}

	return curLoop;
};

Sizzle.error = function( msg ) {
	throw "Syntax error, unrecognized expression: " + msg;
};

var Expr = Sizzle.selectors = {
	order: [ "ID", "NAME", "TAG" ],
	match: {
		ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
		CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
		NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
		ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
		TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
		CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/,
		POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
		PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
	},
	leftMatch: {},
	attrMap: {
		"class": "className",
		"for": "htmlFor"
	},
	attrHandle: {
		href: function(elem){
			return elem.getAttribute("href");
		}
	},
	relative: {
		"+": function(checkSet, part){
			var isPartStr = typeof part === "string",
				isTag = isPartStr && !/\W/.test(part),
				isPartStrNotTag = isPartStr && !isTag;

			if ( isTag ) {
				part = part.toLowerCase();
			}

			for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
				if ( (elem = checkSet[i]) ) {
					while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}

					checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
						elem || false :
						elem === part;
				}
			}

			if ( isPartStrNotTag ) {
				Sizzle.filter( part, checkSet, true );
			}
		},
		">": function(checkSet, part){
			var isPartStr = typeof part === "string",
				elem, i = 0, l = checkSet.length;

			if ( isPartStr && !/\W/.test(part) ) {
				part = part.toLowerCase();

				for ( ; i < l; i++ ) {
					elem = checkSet[i];
					if ( elem ) {
						var parent = elem.parentNode;
						checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
					}
				}
			} else {
				for ( ; i < l; i++ ) {
					elem = checkSet[i];
					if ( elem ) {
						checkSet[i] = isPartStr ?
							elem.parentNode :
							elem.parentNode === part;
					}
				}

				if ( isPartStr ) {
					Sizzle.filter( part, checkSet, true );
				}
			}
		},
		"": function(checkSet, part, isXML){
			var doneName = done++, checkFn = dirCheck, nodeCheck;

			if ( typeof part === "string" && !/\W/.test(part) ) {
				part = part.toLowerCase();
				nodeCheck = part;
				checkFn = dirNodeCheck;
			}

			checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
		},
		"~": function(checkSet, part, isXML){
			var doneName = done++, checkFn = dirCheck, nodeCheck;

			if ( typeof part === "string" && !/\W/.test(part) ) {
				part = part.toLowerCase();
				nodeCheck = part;
				checkFn = dirNodeCheck;
			}

			checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML);
		}
	},
	find: {
		ID: function(match, context, isXML){
			if ( typeof context.getElementById !== "undefined" && !isXML ) {
				var m = context.getElementById(match[1]);
				return m ? [m] : [];
			}
		},
		NAME: function(match, context){
			if ( typeof context.getElementsByName !== "undefined" ) {
				var ret = [], results = context.getElementsByName(match[1]);

				for ( var i = 0, l = results.length; i < l; i++ ) {
					if ( results[i].getAttribute("name") === match[1] ) {
						ret.push( results[i] );
					}
				}

				return ret.length === 0 ? null : ret;
			}
		},
		TAG: function(match, context){
			return context.getElementsByTagName(match[1]);
		}
	},
	preFilter: {
		CLASS: function(match, curLoop, inplace, result, not, isXML){
			match = " " + match[1].replace(/\\/g, "") + " ";

			if ( isXML ) {
				return match;
			}

			for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
				if ( elem ) {
					if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) {
						if ( !inplace ) {
							result.push( elem );
						}
					} else if ( inplace ) {
						curLoop[i] = false;
					}
				}
			}

			return false;
		},
		ID: function(match){
			return match[1].replace(/\\/g, "");
		},
		TAG: function(match, curLoop){
			return match[1].toLowerCase();
		},
		CHILD: function(match){
			if ( match[1] === "nth" ) {
				// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
				var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
					match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
					!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);

				// calculate the numbers (first)n+(last) including if they are negative
				match[2] = (test[1] + (test[2] || 1)) - 0;
				match[3] = test[3] - 0;
			}

			// TODO: Move to normal caching system
			match[0] = done++;

			return match;
		},
		ATTR: function(match, curLoop, inplace, result, not, isXML){
			var name = match[1].replace(/\\/g, "");
			
			if ( !isXML && Expr.attrMap[name] ) {
				match[1] = Expr.attrMap[name];
			}

			if ( match[2] === "~=" ) {
				match[4] = " " + match[4] + " ";
			}

			return match;
		},
		PSEUDO: function(match, curLoop, inplace, result, not){
			if ( match[1] === "not" ) {
				// If we're dealing with a complex expression, or a simple one
				if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
					match[3] = Sizzle(match[3], null, null, curLoop);
				} else {
					var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
					if ( !inplace ) {
						result.push.apply( result, ret );
					}
					return false;
				}
			} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
				return true;
			}
			
			return match;
		},
		POS: function(match){
			match.unshift( true );
			return match;
		}
	},
	filters: {
		enabled: function(elem){
			return elem.disabled === false && elem.type !== "hidden";
		},
		disabled: function(elem){
			return elem.disabled === true;
		},
		checked: function(elem){
			return elem.checked === true;
		},
		selected: function(elem){
			// Accessing this property makes selected-by-default
			// options in Safari work properly
			elem.parentNode.selectedIndex;
			return elem.selected === true;
		},
		parent: function(elem){
			return !!elem.firstChild;
		},
		empty: function(elem){
			return !elem.firstChild;
		},
		has: function(elem, i, match){
			return !!Sizzle( match[3], elem ).length;
		},
		header: function(elem){
			return (/h\d/i).test( elem.nodeName );
		},
		text: function(elem){
			return "text" === elem.type;
		},
		radio: function(elem){
			return "radio" === elem.type;
		},
		checkbox: function(elem){
			return "checkbox" === elem.type;
		},
		file: function(elem){
			return "file" === elem.type;
		},
		password: function(elem){
			return "password" === elem.type;
		},
		submit: function(elem){
			return "submit" === elem.type;
		},
		image: function(elem){
			return "image" === elem.type;
		},
		reset: function(elem){
			return "reset" === elem.type;
		},
		button: function(elem){
			return "button" === elem.type || elem.nodeName.toLowerCase() === "button";
		},
		input: function(elem){
			return (/input|select|textarea|button/i).test(elem.nodeName);
		}
	},
	setFilters: {
		first: function(elem, i){
			return i === 0;
		},
		last: function(elem, i, match, array){
			return i === array.length - 1;
		},
		even: function(elem, i){
			return i % 2 === 0;
		},
		odd: function(elem, i){
			return i % 2 === 1;
		},
		lt: function(elem, i, match){
			return i < match[3] - 0;
		},
		gt: function(elem, i, match){
			return i > match[3] - 0;
		},
		nth: function(elem, i, match){
			return match[3] - 0 === i;
		},
		eq: function(elem, i, match){
			return match[3] - 0 === i;
		}
	},
	filter: {
		PSEUDO: function(elem, match, i, array){
			var name = match[1], filter = Expr.filters[ name ];

			if ( filter ) {
				return filter( elem, i, match, array );
			} else if ( name === "contains" ) {
				return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0;
			} else if ( name === "not" ) {
				var not = match[3];

				for ( var j = 0, l = not.length; j < l; j++ ) {
					if ( not[j] === elem ) {
						return false;
					}
				}

				return true;
			} else {
				Sizzle.error( "Syntax error, unrecognized expression: " + name );
			}
		},
		CHILD: function(elem, match){
			var type = match[1], node = elem;
			switch (type) {
				case 'only':
				case 'first':
					while ( (node = node.previousSibling) )	 {
						if ( node.nodeType === 1 ) { 
							return false; 
						}
					}
					if ( type === "first" ) { 
						return true; 
					}
					node = elem;
				case 'last':
					while ( (node = node.nextSibling) )	 {
						if ( node.nodeType === 1 ) { 
							return false; 
						}
					}
					return true;
				case 'nth':
					var first = match[2], last = match[3];

					if ( first === 1 && last === 0 ) {
						return true;
					}
					
					var doneName = match[0],
						parent = elem.parentNode;
	
					if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
						var count = 0;
						for ( node = parent.firstChild; node; node = node.nextSibling ) {
							if ( node.nodeType === 1 ) {
								node.nodeIndex = ++count;
							}
						} 
						parent.sizcache = doneName;
					}
					
					var diff = elem.nodeIndex - last;
					if ( first === 0 ) {
						return diff === 0;
					} else {
						return ( diff % first === 0 && diff / first >= 0 );
					}
			}
		},
		ID: function(elem, match){
			return elem.nodeType === 1 && elem.getAttribute("id") === match;
		},
		TAG: function(elem, match){
			return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match;
		},
		CLASS: function(elem, match){
			return (" " + (elem.className || elem.getAttribute("class")) + " ")
				.indexOf( match ) > -1;
		},
		ATTR: function(elem, match){
			var name = match[1],
				result = Expr.attrHandle[ name ] ?
					Expr.attrHandle[ name ]( elem ) :
					elem[ name ] != null ?
						elem[ name ] :
						elem.getAttribute( name ),
				value = result + "",
				type = match[2],
				check = match[4];

			return result == null ?
				type === "!=" :
				type === "=" ?
				value === check :
				type === "*=" ?
				value.indexOf(check) >= 0 :
				type === "~=" ?
				(" " + value + " ").indexOf(check) >= 0 :
				!check ?
				value && result !== false :
				type === "!=" ?
				value !== check :
				type === "^=" ?
				value.indexOf(check) === 0 :
				type === "$=" ?
				value.substr(value.length - check.length) === check :
				type === "|=" ?
				value === check || value.substr(0, check.length + 1) === check + "-" :
				false;
		},
		POS: function(elem, match, i, array){
			var name = match[2], filter = Expr.setFilters[ name ];

			if ( filter ) {
				return filter( elem, i, match, array );
			}
		}
	}
};

var origPOS = Expr.match.POS,
	fescape = function(all, num){
		return "\\" + (num - 0 + 1);
	};

for ( var type in Expr.match ) {
	Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
	Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
}

var makeArray = function(array, results) {
	array = Array.prototype.slice.call( array, 0 );

	if ( results ) {
		results.push.apply( results, array );
		return results;
	}
	
	return array;
};

// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try {
	Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;

// Provide a fallback method if it does not work
} catch(e){
	makeArray = function(array, results) {
		var ret = results || [], i = 0;

		if ( toString.call(array) === "[object Array]" ) {
			Array.prototype.push.apply( ret, array );
		} else {
			if ( typeof array.length === "number" ) {
				for ( var l = array.length; i < l; i++ ) {
					ret.push( array[i] );
				}
			} else {
				for ( ; array[i]; i++ ) {
					ret.push( array[i] );
				}
			}
		}

		return ret;
	};
}

var sortOrder;

if ( document.documentElement.compareDocumentPosition ) {
	sortOrder = function( a, b ) {
		if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
			if ( a == b ) {
				hasDuplicate = true;
			}
			return a.compareDocumentPosition ? -1 : 1;
		}

		var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1;
		if ( ret === 0 ) {
			hasDuplicate = true;
		}
		return ret;
	};
} else if ( "sourceIndex" in document.documentElement ) {
	sortOrder = function( a, b ) {
		if ( !a.sourceIndex || !b.sourceIndex ) {
			if ( a == b ) {
				hasDuplicate = true;
			}
			return a.sourceIndex ? -1 : 1;
		}

		var ret = a.sourceIndex - b.sourceIndex;
		if ( ret === 0 ) {
			hasDuplicate = true;
		}
		return ret;
	};
} else if ( document.createRange ) {
	sortOrder = function( a, b ) {
		if ( !a.ownerDocument || !b.ownerDocument ) {
			if ( a == b ) {
				hasDuplicate = true;
			}
			return a.ownerDocument ? -1 : 1;
		}

		var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange();
		aRange.setStart(a, 0);
		aRange.setEnd(a, 0);
		bRange.setStart(b, 0);
		bRange.setEnd(b, 0);
		var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange);
		if ( ret === 0 ) {
			hasDuplicate = true;
		}
		return ret;
	};
}

// Utility function for retreiving the text value of an array of DOM nodes
Sizzle.getText = function( elems ) {
	var ret = "", elem;

	for ( var i = 0; elems[i]; i++ ) {
		elem = elems[i];

		// Get the text from text nodes and CDATA nodes
		if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
			ret += elem.nodeValue;

		// Traverse everything else, except comment nodes
		} else if ( elem.nodeType !== 8 ) {
			ret += Sizzle.getText( elem.childNodes );
		}
	}

	return ret;
};

// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){
	// We're going to inject a fake input element with a specified name
	var form = document.createElement("div"),
		id = "script" + (new Date()).getTime();
	form.innerHTML = "<a name='" + id + "'/>";

	// Inject it into the root element, check its status, and remove it quickly
	var root = document.documentElement;
	root.insertBefore( form, root.firstChild );

	// The workaround has to do additional checks after a getElementById
	// Which slows things down for other browsers (hence the branching)
	if ( document.getElementById( id ) ) {
		Expr.find.ID = function(match, context, isXML){
			if ( typeof context.getElementById !== "undefined" && !isXML ) {
				var m = context.getElementById(match[1]);
				return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : [];
			}
		};

		Expr.filter.ID = function(elem, match){
			var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
			return elem.nodeType === 1 && node && node.nodeValue === match;
		};
	}

	root.removeChild( form );
	root = form = null; // release memory in IE
})();

(function(){
	// Check to see if the browser returns only elements
	// when doing getElementsByTagName("*")

	// Create a fake element
	var div = document.createElement("div");
	div.appendChild( document.createComment("") );

	// Make sure no comments are found
	if ( div.getElementsByTagName("*").length > 0 ) {
		Expr.find.TAG = function(match, context){
			var results = context.getElementsByTagName(match[1]);

			// Filter out possible comments
			if ( match[1] === "*" ) {
				var tmp = [];

				for ( var i = 0; results[i]; i++ ) {
					if ( results[i].nodeType === 1 ) {
						tmp.push( results[i] );
					}
				}

				results = tmp;
			}

			return results;
		};
	}

	// Check to see if an attribute returns normalized href attributes
	div.innerHTML = "<a href='#'></a>";
	if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
			div.firstChild.getAttribute("href") !== "#" ) {
		Expr.attrHandle.href = function(elem){
			return elem.getAttribute("href", 2);
		};
	}

	div = null; // release memory in IE
})();

if ( document.querySelectorAll ) {
	(function(){
		var oldSizzle = Sizzle, div = document.createElement("div");
		div.innerHTML = "<p class='TEST'></p>";

		// Safari can't handle uppercase or unicode characters when
		// in quirks mode.
		if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
			return;
		}
	
		Sizzle = function(query, context, extra, seed){
			context = context || document;

			// Only use querySelectorAll on non-XML documents
			// (ID selectors don't work in non-HTML documents)
			if ( !seed && context.nodeType === 9 && !Sizzle.isXML(context) ) {
				try {
					return makeArray( context.querySelectorAll(query), extra );
				} catch(e){}
			}
		
			return oldSizzle(query, context, extra, seed);
		};

		for ( var prop in oldSizzle ) {
			Sizzle[ prop ] = oldSizzle[ prop ];
		}

		div = null; // release memory in IE
	})();
}

(function(){
	var div = document.createElement("div");

	div.innerHTML = "<div class='test e'></div><div class='test'></div>";

	// Opera can't find a second classname (in 9.6)
	// Also, make sure that getElementsByClassName actually exists
	if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
		return;
	}

	// Safari caches class attributes, doesn't catch changes (in 3.2)
	div.lastChild.className = "e";

	if ( div.getElementsByClassName("e").length === 1 ) {
		return;
	}
	
	Expr.order.splice(1, 0, "CLASS");
	Expr.find.CLASS = function(match, context, isXML) {
		if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
			return context.getElementsByClassName(match[1]);
		}
	};

	div = null; // release memory in IE
})();

function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
	for ( var i = 0, l = checkSet.length; i < l; i++ ) {
		var elem = checkSet[i];
		if ( elem ) {
			elem = elem[dir];
			var match = false;

			while ( elem ) {
				if ( elem.sizcache === doneName ) {
					match = checkSet[elem.sizset];
					break;
				}

				if ( elem.nodeType === 1 && !isXML ){
					elem.sizcache = doneName;
					elem.sizset = i;
				}

				if ( elem.nodeName.toLowerCase() === cur ) {
					match = elem;
					break;
				}

				elem = elem[dir];
			}

			checkSet[i] = match;
		}
	}
}

function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
	for ( var i = 0, l = checkSet.length; i < l; i++ ) {
		var elem = checkSet[i];
		if ( elem ) {
			elem = elem[dir];
			var match = false;

			while ( elem ) {
				if ( elem.sizcache === doneName ) {
					match = checkSet[elem.sizset];
					break;
				}

				if ( elem.nodeType === 1 ) {
					if ( !isXML ) {
						elem.sizcache = doneName;
						elem.sizset = i;
					}
					if ( typeof cur !== "string" ) {
						if ( elem === cur ) {
							match = true;
							break;
						}

					} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
						match = elem;
						break;
					}
				}

				elem = elem[dir];
			}

			checkSet[i] = match;
		}
	}
}

Sizzle.contains = document.compareDocumentPosition ? function(a, b){
	return !!(a.compareDocumentPosition(b) & 16);
} : function(a, b){
	return a !== b && (a.contains ? a.contains(b) : true);
};

Sizzle.isXML = function(elem){
	// documentElement is verified for cases where it doesn't yet exist
	// (such as loading iframes in IE - #4833) 
	var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
	return documentElement ? documentElement.nodeName !== "HTML" : false;
};

var posProcess = function(selector, context){
	var tmpSet = [], later = "", match,
		root = context.nodeType ? [context] : context;

	// Position selectors must be done after the filter
	// And so must :not(positional) so we move all PSEUDOs to the end
	while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
		later += match[0];
		selector = selector.replace( Expr.match.PSEUDO, "" );
	}

	selector = Expr.relative[selector] ? selector + "*" : selector;

	for ( var i = 0, l = root.length; i < l; i++ ) {
		Sizzle( selector, root[i], tmpSet );
	}

	return Sizzle.filter( later, tmpSet );
};

// EXPOSE

return Sizzle(selector, context, results, seed);

};

function $addFlash(showId,flashSrc,flashW,flashH){
//显示flash
	$id(showId).innerHTML='<embed src="'+flashSrc+'" height="'+flashH+'" width="'+flashW+'" wmode="transparent" type="application/x-shockwave-flash"></embed>';
}

function $getStrBetween(str,sBegin,sEnd){
	var bp=str.indexOf(sBegin);
	if(bp==-1){
		return("");
	}
	bp+=sBegin.length;
	var ep=str.indexOf(sEnd,bp);
	if(ep==-1){
		return("");
	}
	return str.substr(bp,ep-bp);
}

function $picPreview(picList, id, maxh, maxw) {
//商品图片大图查看功能
    var t = [];
    for (var i = 0; i < picList.length; i++) {
        (picList[i] != "") ? t.push(picList[i]) : "";
    }
    picList = t;
    //显示遮罩
    var page = (picList.length > 1) ? true : false;
    var cId = id; //当前图片编号

    var picHtml = '<table width="100%" height="' + maxh + '" border="0" cellpadding="0" cellspacing="0" style="background-color:#ffffff"><tr><td width="60" align="center" valign="top"  style="display:none;"><br /><br /><input id="pp1" type="button" value=" << " style="line-height:25px;"/></td><td align="center" valign="middle" ><div id="pp3" style="width:720px;overflow:hidden;"></div></td><td width="60" align="center" valign="top"   style="display:none;"><br /><br /><input id="pp2" type="button" style="line-height:25px;" value=" >> "/></td></tr></table>'

    var al = $float({
        title: "",
        html: picHtml,
        fix: true,
        width: maxw + (page ? 160 : 60),
        height: maxh + 80,
        style: "stand", //stand\none\poptip
        cover: true	//显示
    });

    $$("#floatCover").css("z-index", "3000");
    $$("#floatBox_" + al.id).css("z-index", "4000");

    var l1 = $$("#pp1"), l2 = $$("#pp2"), l3 = $$("#pp3");
    if (page) {
        l2.add(l1).click(function () {
            showPic((this.id == l1.attr("id")) ? parseInt(cId) - 1 : parseInt(cId) + 1);
        }).parent("td").show();
    }
    //显示首张图片，并resize
    showPic(id);
    //根据情况显示上一页等其他的相关控制信息，并resize
    function showPic(id) {
        //编号不正确的情况
        if (id < 0 || id > picList.length - 1) {
            return;
        }
        l3.html('<img src="' + picList[id] + '" alt="点击图片可关闭大图" id="pp4" />');
        $$("#pp4").click(function () {
            al.close();
        }).one("load", function () {
            $reSizeImg(this, maxw, maxh);
            al.width = this.width + (page ? 120 : 0);
            al.height = this.height + 25;
            al.width = (al.width < maxw + (page ? 120 : 0)) ? maxw + (page ? 120 : 0) : al.width;
            al.height = (al.height < maxh + 25) ? maxh + 25 : al.height;
            //al.resize();
        }).one("error", function () {
            al.width = maxw; al.height = maxh + 25;
        });
        cId = id;
        l1.attr("disabled", (cId == 0) ? "disabled" : "");
        l2.attr("disabled", (cId == picList.length - 1) ? "disabled" : "");
    }
};

function $hasClass(old,cur){
	if(!old||!cur) return null;
	var arr=old.split(' ');
	for(var i=0,len=arr.length;i<len;i++){
		if(cur==arr[i]){
			return cur;
		}
	};
	return null;
}

(function(){
    var	isBind=false,
        heightList=[],
        funcList=[],
        optList=[],
        visibleH=document.documentElement.clientHeight;//浏览器高度
    
    $scroll=function(opt){
        var height=opt.height?opt.height:$getY($id(opt.id));
        if(visibleH<height){
            heightList.push(height*1);
            funcList.push(opt.func);
            optList.push(opt);
        }else{
            //如果设置的值本身就小于屏幕的值，那就没有必要压入了，直接执行
            opt.func(opt);
        };
        
        
        //如果已经绑定onscroll，无需重复绑定
        if(isBind){
            isBind=true;
        }else{
            $addEvent(window,'scroll',doScroll);
            $addEvent(window,'resize',doResize);
        };
        
		function doResize(){
			visibleH=document.documentElement.clientHeight;
			doScroll();
		};
		
        function doScroll(){
			var len=heightList.length;
			if(len===0){
				$delEvent(window,'scroll',doScroll);
            	$delEvent(window,'resize',doScroll);
				return null;
			};
			
			var	dv 		= document.defaultView,
			 	y 		= (dv) ? dv.pageYOffset : 0,
				h 		= Math.max(document.body.scrollTop,document.documentElement.scrollTop,y) + visibleH,//可见范围
				arrHeight=[],
				arrFunc=[],
				arrOpt=[];
		    for(var i=0;i<len;i++){
                if(h > heightList[i]){
                    //无论是否需要，把传入进来的opt再传入调用函数
                   funcList[i](optList[i]);
				   //把已经操作完成的出栈
                }else{
					arrHeight.push(heightList[i]);
					arrFunc.push(funcList[i]);
					arrOpt.push(optList[i]);
				}
            };
			heightList=arrHeight;
			funcList=arrFunc;
			optList=arrOpt;
        }
    };
})();

function $empty(){
//返回全局空函数，不做任何事情，返回true；
   if(!window["_PP_core_empty"]){
       window["_PP_core_empty"]=function(){return true;}
   }
   return window["_PP_core_empty"];
}

function $floatSub(arg1,arg2){
//浮点数减法运算   
 var r1,r2,m,n;  
 try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}  
 try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}  
 m=Math.pow(10,Math.max(r1,r2));  
 //动态控制精度长度  
 n=(r1>=r2)?r1:r2;  
 return ((arg1*m-arg2*m)/m).toFixed(n);  
}

function $mouseover(obj,func){
	obj.onmouseover=function(e){
		var e=window.event||e,
			target=e.fromElement || e.relatedTarget,
			parent=target;
		while ( parent && parent !== this ) {
			parent = parent.parentNode;
		}	
		if ( parent !== this ) {
			func(this);
		}
	}
}

function $mouseout(obj,func){
	obj.onmouseout=function(e){
		var e=window.event||e,
			target=e.toElement || e.relatedTarget,
			parent=target;
		while ( parent && parent !== this ) {
			parent = parent.parentNode;
		}	
		if ( parent !== this ) {
			func(this);
		}
	}
}

function $purge(d) {
    var a = d.attributes, i, l, n;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            n = a[i].name;
            if (typeof d[n] === 'function') {
                d[n] = null;
            }
        }
    }
    a = d.childNodes;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            purge(d.childNodes[i]);
        }
    }
}

function $destoryDomEvents(d) {
    var a = d.attributes, i, l, n;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            if (a[i]) {
                n = a[i].name;
                if (typeof d[n] === 'function') {
                    d[n] = null;
                }
            }
        }
    }
    a = d.childNodes;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            $destoryDomEvents(d.childNodes[i]);
        }
    }
};

function $ajax(opt) {
	/*本函数基于QZFL.XHR实现*/
	var o={
		url:'', 	//请求地址
		method:'GET', 	//发送方式，除非指明POST，否则全部为GET
		data:null, 		//hashTable形式的字典
		type:"text",	//返回类型,text/xml/json
		cache:false,	//是否缓存，默认不缓存
		autoToken:true,	//是否自动为请求加上token
		onSuccess:$empty(),
		onError:$empty(),
        onComplete:$empty(),
		beforeSend:$empty()//发送请求前所执行的函数,一般用于修改header，参数是XMLHttpRequest对象
	};	
	//合并参数
	for(var key in opt){
		o[key]=opt[key]
	};

	o.method = (typeof(o.method) != "string" || o.method.toUpperCase() != "POST")?"GET":"POST";
	o.data   = $makeUrl(o.data);
	
	if(o.method == 'POST' && o.data == null) {
		return false;
	}	
	
	if(o.method == 'GET' && o.data){
		o.url += (o.url.indexOf("?") < 0 ? "?"  : "&") +  o.data;
	}	
	
	o.xhr = $xhrMaker();

	if(o.xhr===null){
		return false;
	}
	
	if(o.autoToken){
		o.url=$addToken(o.url,"ajax");
	}

	try {
		o.xhr.open(o.method, o.url, true);
	} catch (e) {
		return false;
	}
	
	if (o.method == 'POST') {
		o.xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	}
	
	if (!o.cache) {
		o.xhr.setRequestHeader('If-Modified-Since', 'Thu, 1 Jan 1970 00:00:00 GMT');
		o.xhr.setRequestHeader('Cache-Control', 'no-cache');
	}
	
	o.xhr.onreadystatechange = function() {
		try {
			if (o.xhr.readyState == 4) {
				if (o.xhr.status >= 200 && o.xhr.status < 300) {
					var backData=o.xhr.responseText;
					switch(o.type){
						case "json":
							//backData=eval('('+backData+')');
							backData = (new Function("return (" + backData + ")"))();
							break;
						case "xml":
							backData=o.xhr.responseXML;
							break
					}
					o.onSuccess(backData);
				} else {
					o.onError(o.xhr.status);
				}
                o.onComplete(o.xhr.status);
				delete o.xhr;
			}
		} catch (e) {}
	};
	
	o.beforeSend(o.xhr);
	
	o.xhr.send(o.method == 'POST' ? o.data : null);
};

function $addZero(v,size){
	for(var i=0,len=size-(v+"").length;i<len;i++){
		v="0"+v;
	};
	return v;
}

function $replace(tpl, argsArray){
	var _t = tpl;
        for(var i=0,len=argsArray.length; i<len; i++){
                var curr = argsArray[i];
		_t = _t.replace(curr[0], curr[1]);
	}
	return _t;
}

function $getWeekNumOfYear(){
	var today = new Date();
	var end = new Date(today.getFullYear(),today.getMonth(),today.getDate());
	var start = new Date(today.getFullYear(),0,1);
	var d = Math.round((end -start)/86400000);
	return Math.ceil((start.getDay()+d-today.getDay())/7+1);
};

function $getQuerySafe(name, url) {
    var s = escape($getQuery(name, url));
    s=s.replace(/[\?|#].*/, "").replace(/(%23|%3F).*/i,"").replace(/(%2523|%253F).*/i,""); 
    return s
}


function $getActiveInfoByStr(msg){
    //根据抽奖接口返回的信息同系统标准提示和运营自定义提示做匹配，返回正确提示
    var smsg=window.activeErrMsg_text;
    var umsg=window.user_text?window.user_text:window.activeErrMsg_text;
    var index=-1;
    for(var i=0,j=smsg.length;i<j;i++){
        if(smsg[i]==msg){
            index=i;
        }
    }
    return (umsg[index]&&(index>=0))?umsg[index]:"系统错误，请稍后再试！";
}

function $bindActiveObjects(){
    //初始化市场活动的按钮及输入框相关操作
    $$("#activeQQClicker,#activeOrderClicker").live("click",function(){
        //QQ号抽奖活动
        var activeId=$$(this).attr("activeId");
        if(this.id=="activeQQClicker"){
            var level=$$(this).attr("level");
            if(level){
                $$("#level").val(level)
            };
            if(activeId){
                window.g_sActive=activeId;
            }
            $activeRaffleByQQ();
        }
        //订单号抽奖活动
        if(this.id=="activeOrderClicker"){
            if(activeId){
                window.g_sActive=activeId;
            }
            $activeRaffleByOrderId();
        }
    });
	var defalutVal="";
    //订单号输入框事件绑定
    $$("#deal_id").focus(function(){
        var _t=$$(this),
			val=_t.val();
        _t.css("color","#000");
        if(val.indexOf("填写")!=-1){
			defalutVal=val;
            _t.val("");
        }
    }).blur(function(){
        var _t=$$(this),
			val=_t.val();
        if(val=="" ||val.indexOf('填写')!=-1){
            _t.val(defalutVal).css("color","#ccc");
        }else{
            _t.css("color","#000");
        }
    }).blur();
}

function $showGotopButton(){
	//显示一个回到顶部的浮动按钮
	$$(document).ready(function(){
		$$("body").append("<a href='#' class='toTop' title='回到顶部'  id='flowLink' style='top:587px;right:50%; position:absolute; margin-right:-502px; width:25px; height:80px;'><img src='http://paipai.lady.qq.com/images/magazine6/totop_03.jpg' /></a>");
		window._gotopLy=0
		window._gotopItem=document.getElementById("flowLink");
		setInterval(function(){
			var f=window._gotopItem;
			var y =((document.documentElement)?document.documentElement.scrollTop:document.body.scrollTop);
			temp=.1*(y-window._gotopLy); 
			temp=((temp>0)?Math.ceil(temp):Math.floor(temp)); 
			f.style.top=(parseInt(f.style.top)+temp)+"px";
			window._gotopLy+=temp; 
		},10)
	});
}

function $parseUrl(url) {
    var a =  document.createElement('a');
    a.href = url;
    return {
        source: url,
        protocol: a.protocol.replace(':',''),
        host: a.hostname,
        port: a.port,
        query: a.search,
        params: (function(){
            var ret = {},
                seg = a.search.replace(/^\?/,'').split('&'),
                len = seg.length, i = 0, s;
            for (;i<len;i++) {
                if (!seg[i]) { continue; }
                s = seg[i].split('=');
                ret[s[0]] = s[1];
            }
            return ret;
        })(),
        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
        hash: a.hash.replace('#',''),
        path: a.pathname.replace(/^([^\/])/,'/$1'),
        relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
        segments: a.pathname.replace(/^\//,'').split('/')
    };
}

function $parseDate(str){
	return Date.parse(str.split('-').join('/'))
}

function $attr(attr,val,node){
	var results=[],
		node=node||document.body;
		
	walk(node,function(n){
		var actual=n.nodeType===1&&(attr==="class"?n.className:n.getAttribute(attr));
		if(typeof actual === 'string' && (actual === val || typeof val !== 'string')){
				results.push(n);
		}
	});
	
	return results;

	function walk(n,func){
		func(n);
		n=n.firstChild;
		while(n){
			walk(n,func);
			n=n.nextSibling;
		}
	}
}

function $simulateSelect(option){
	var opt={
		input:"",	//输入框id
		show:"",	//显示id
		cover:"",	//遮盖iframe的id
		button:"",	//提交的按钮
		onSearch:$empty(),	//开始搜索的时候
		onSumit:$empty()	//提交的时候调用
	};

	for(var k in option){
		opt[k]=option[k];
	};
	
	var	nowItem=-1,		//当前展示的项目
		preItem=0,		//前一项
		total=0,		//总项目
		val="",			//存储进行搜索的值，如果没有变化则不启动
		oInput=$id(opt.input),	//存储输入的dom
		oShow=$id(opt.show),		//存储展示位置的dom
		oBtn=$id(opt.button);	//存储按钮的dom
		
	$addEvent(document,"click",function(){
		//鼠标外部点击后隐藏搜索和选择的下拉框
		if(oShow.style.display!="none"){
			hideResult();	
		}
	});

	function hideResult(){
		//隐藏搜索结果列表
		$display(opt.show+","+opt.cover,"none");	
	};
	
	oInput.onkeyup=function(e){
		var	code=$getKeyCode(e);
		if(code!==13 && code!==38 && code!==40 && this.value!==''){
			if(this.value!==val){
				hideResult();	
				opt.onSearch(this.value,opt);
			};
		}else if(code==13){
			opt.onSumit();
		}else if(this.value==''){ 
			hideResult();				
		};
		val=this.value;
	};
	
	null!==oBtn?(oBtn.onclick=function(){
		opt.onSumit(); 
	}):"";
	
	opt.showResult=function(html,data){
		oShow.innerHTML=html;
		$display(opt.show+","+opt.cover,'block');
		nowItem=-1;
		preItem=0;
		total=data.length;
		oInput.onkeydown=function(e){
			showKeyDown($getKeyCode(e));
		}
		
		function showKeyDown(code){
			//选择搜索结果的操作
			if(code==38||code==40){
				//38:up,40:down
				preItem=nowItem;
				code==38?nowItem--:nowItem++;
				nowItem=nowItem<0?total-1:(nowItem>total-1?0:nowItem);
	
				var oItem=oShow.childNodes[0].childNodes[nowItem];
				if(oItem){
					oItem.className="autoResultLink";
					oInput.value=data[nowItem];
				};
				if(-1!==preItem){
					var oPrev=oShow.childNodes[0].childNodes[preItem];
					oPrev?oPrev.className="":"";
				}				
			}else if(code==13){
				//回车
				if(nowItem!=-1){
					oInput.value=data[nowItem];
					hideResult();
				};
				opt.onSumit(); 
			}
		};	
	}
}

function $getYP(e){
	//获取页面中对象的绝对Y位置，如果是隐藏的，则尝试获取其父节点位置
	var t = $getY(e),e = e.parentNode;   
	
	while(0===t && document.body != e){
		t = $getY(e);   
		e = e.parentNode;
	}
	
    return t;
}

function $getTimeDistance(ts){
//根据时间差计算剩余的时间，返回[天，小时，分，秒]
	  var timeLeft=[0,0,0,0];//结构：天、小时、分、秒
	  timeLeft[0]=(ts>86400)?parseInt(ts/86400):0;
	  ts=ts - timeLeft[0] * 86400;
	  timeLeft[1]=(ts>3600)?parseInt(ts/3600):0;
	  ts=ts - timeLeft[1] * 3600;
	  timeLeft[2]=(ts>60)?parseInt(ts/60):0;
	  timeLeft[3]=ts - timeLeft[2] * 60;
	  return timeLeft;
}

(function(){
	var	isReady=false, //判断onDOMReady方法是否已经被执行过
    	readyList= [],//把需要执行的方法先暂存在这个数组里
        timer;//定时器句柄
	$ready=function(fn) {
		if (isReady )
			fn.call( document);
		else
			readyList.push(function() { return fn.call(this);});
		return this;
	}
        
	var onDOMReady=function(){
		for(var i=0,len=readyList.length;i<len;i++){
			readyList[i].apply(document);
		}
		readyList = null;
	}
	
	var bindReady = function(evt){
		if(isReady) return;
		isReady=true;
		onDOMReady.call(window);
		if(document.removeEventListener){
			document.removeEventListener("DOMContentLoaded", bindReady, false);
		}else if(document.attachEvent){
			document.detachEvent("onreadystatechange", bindReady);
			if(window == window.top){
				clearInterval(timer);
				timer = null;
			}
		}
	};
	if(document.addEventListener){
		document.addEventListener("DOMContentLoaded", bindReady, false);
	}else if(document.attachEvent){
		document.attachEvent("onreadystatechange", function(){
			if((/loaded|complete/).test(document.readyState)){
				bindReady();
			}
		});
		if(window == window.top){
			timer = setInterval(function(){
					try{
						isReady||document.documentElement.doScroll('left');//在IE下用能否执行doScroll判断dom是否加载完毕
					}catch(e){
						return;
					}
					bindReady();
			},5);
		}
	}
})();

function $hover(option){
	var opt={
		title:null,//dom
		content:null,//dom
		overFunc:$empty(),
		outFunc:$empty(),
		timer:100,
		intr:null
	};
	for(var k in option){
		opt[k]=option[k];
	};
	
	$mouseover(opt.title,overFunc);
	$mouseout(opt.title,outFunc);
	$mouseover(opt.content,overFunc);
	$mouseout(opt.content,outFunc);
	
	function overFunc(){
		clearTimeout(opt.intr);
		opt.intr = null;
		opt.content.style.display="block"
		opt.overFunc(opt);
	}
	
	function outFunc(){
		opt.intr=setTimeout(function(){
			opt.content.style.display="none"
			opt.outFunc(opt);
		},opt.timer);
	}	
}

function $each(jn,fn){
	var len=jn.length;
	if("number"===typeof len){
		for(var i=0;i<len;i++){
			fn(jn[i],i);
		}
	}else{
		for(var k in jn){
			fn(jn[k],k);
		}	
	}
};

function $createXmlObj(){
	//构造xml对象
	var tempObj;
	if (document.all){
		var arrXMLDom = ["MSXML2.DOMDocument.4.0","Microsoft.XmlDom"];
		for (var i = 0; i < arrXMLDom.length; i++){
			try{
				tempObj = new ActiveXObject(arrXMLDom[i]);
				tempObj.async = false;
				return tempObj;
			}catch (e){}
		}
	}else{
		tempObj = document.implementation.createDocument("", "", null);
		tempObj.async = false;
		return tempObj;
	}
}

function $loadXmlString(s){
	//加载xml字符串，转成xml对象

	var tempObj = $createXmlObj();
	if (document.all){
		if (tempObj){
			tempObj.loadXML(s);
		}
	}else{
		var oParser = new DOMParser();
		tempObj = oParser.parseFromString(s,"text/xml");
	}
	return tempObj;
}

function $qq2Commid(qq){
	//qq号转十六进制的actionId
	qq = parseInt(qq);
	var id = qq.toString(16).toUpperCase();
	var num = 8-id.length;
	for (var i = 0; i<num; i++){
		id = "0"+id;
	}
	id =id.substring(4,8)+id.substring(0,4);
	id =id.substring(2,4)+id.substring(0,2)+id.substring(6,8)+id.substring(4,6);
	for (var j = 0; j<24; j++){
		id = id+"0";
	}
	return id;
}

function $initTabExchange(){
	//初始化tab切换工具
	$$("[tag='tabexchang']").live("mouseover",function(){
		var c=$$(this).attr("content");
		$$("[tag='tabexchang'][groupId='"+$$(this).attr("groupId")+"']").each(function(){
			var ons=$$(this).attr("onstyle");
			var offs=$$(this).attr("offstyle");
			var cont=$$(this).attr("content");
			if(c==cont){//当前的显示出来
				$$(this).removeClass(offs).addClass(ons);
				$$(cont).show();
			}else{
				$$(this).removeClass(ons).addClass(offs);
				$$(cont).hide();
			}
		});
		
	});
}

function $picListShower(opt){
	var option={
		smallShowLength:5,	//小图展示数量
		bigPicArrayIndex:1,		//示意图地址在数组中的index
		smallPicArrayIndex:2,	//小图地址在数组中的index
		floatViewArrayIndex:0,	//浮出图地址在数组中的index
		picViewTemp:'<img title="点击看大图" alt="点击看大图" src="{#url#}" width="300" height="300" id="{#picViewId#}" style="cursor:pointer" />',							//示意图模版
		smallPicTemp:'<li id="{#id#}" {#style#}><img title="点击切换示意图" alt="点击切换示意图" src="{#url#}" style="cursor:pointer;" /></li>',		//小图模板
		floatPicTemp:'<table id="{#floatViewId#}" width="100%" height="500" border="0" cellpadding="0" cellspacing="0"><tr><td width="60" align="center" valign="top"><br /><br /><a href="javascript:;" id="{#previewLastId#}" style="display:none">&lt;&lt;上一张</a></td>  <td align="center" valign="middle"><img src="{#url#}" alt="点击图片可关闭大图" title="点击图片可关闭大图" id="{#floatViewItemId#}" width="450" height="450"/></td><td width="60" align="center" valign="top"><br /><br /><a href="javascript:;" id="{#previewNextId#}" style="display:none">下一张&gt;&gt;</a></td></tr></table>',				//浮出图片模版
		pics:[['','','']],	//图片数据
		picLength:0,		//图片数量
		picView:'',			//示意图dom
		picViewImg:'',		//示意图img对象
		bigPicView:'',		//大图浮窗
		smallView:'',		//小图ul
		smallViewIndex:0,	//小图展示起始index
		currentViewIndex:0,		//展示的index
		fix:true,				//是否在图片长度不足小图展示数量时展示空框
		initPicView:true,		//初始时是否重设示意图，如果html上已经设置则应为false
		smallViewDom:[],	//小图的dom	
		changePics:function(i){},		//换图
		showBigPic:function(i){},		//展示大图
		next:function(){},				//下一张
		prev:function(){},				//上一张
		goHead:function(o){},			//查看的是第一张时调用
		goLast:function(o){},			//查看的是最后一张时调用
		changing:function(o){}			//转换图片后调用
	}
	for(var i in opt){
		option[i]=opt[i];
	}
	option.changePics=changePics;
	option.showBigPic=showBigPic;
	option.next=showNext;
	option.prev=showPrev;
	//图片长度
	option.picLength=option.pics.length;
	//放置示意图
	if(option.picView){
		if(option.initPicView)option.picView.innerHTML=option.picViewTemp.replace(/{#url#}/g,option.pics[0][option.bigPicArrayIndex]).replace(/{#picViewId#}/g,'_picsViewShow');
		//获得img
		var imgList=option.picView.getElementsByTagName('img');
		option.picViewImg=imgList.length>0?imgList[0]:null;
		//展示
		option.picView.onclick=showBigPic;
	}
	//放置小图
	var smallHtml=[];
	for(var i=0;i<option.picLength;i++){
		smallHtml.push(option.smallPicTemp.replace(/{#id#}/g,'_picSmall'+i).replace(/{#style#}/g,i>=option.smallShowLength?'style="display:none;"':'').replace(/{#url#}/g,option.pics[i][option.smallPicArrayIndex]));
	}
	if(option.fix){
		for(var i=option.picLength;i<option.smallShowLength;i++){
			smallHtml.push('<li id="_picSmall'+i+'"></li>');
		}
	}
	if(option.smallView){
		option.smallView.innerHTML=smallHtml.join('');
	}
	//缓存小图对象
	option.smallViewDom=[];
	for(var i=0;i<option.picLength;i++){
		var smallTarget=document.getElementById('_picSmall'+i);
		if(smallTarget){
			option.smallViewDom.push(smallTarget);
			smallTarget.onclick=(function(pi){return function(){changePics(pi)} })(i);
		}
	}
	if(option.picLength>0){
		changePics(0);
	}
	return option;
	function changePics(index){
		//更新小图展示index
		if(option.smallViewIndex+option.smallShowLength<=index){
			option.smallViewIndex=index-option.smallShowLength+1;
		}
		if(option.smallViewIndex>index){
			option.smallViewIndex=option.smallViewIndex-option.smallShowLength+1;
		}
		option.currentViewIndex=index;
		//处理小图的展示
		for(var i=0;i<option.smallViewDom.length;i++){
			//去掉current
			option.smallViewDom[i].className=option.smallViewDom[i].className.replace(/current /ig,'').replace(/ current/ig,'').replace(/current/ig,'');
			if(i>=option.smallViewIndex&&i<option.smallViewIndex+option.smallShowLength){
				//可视范围内
				option.smallViewDom[i].style.display='';
				//当前展示的小图
				if(i==index){
					option.smallViewDom[i].className+=' current';
					//改变示意图
					if(option.picViewImg&&option.picViewImg.src!=option.pics[i][option.bigPicArrayIndex]){
						option.picViewImg.src=option.pics[i][option.bigPicArrayIndex];
					}
				}
			}else{
				//不在可视序号内
				option.smallViewDom[i].style.display='none';
			}
		}
		if(option.changing)option.changing(option);
		if(index==0&&option.goHead)option.goHead(option);
		if(index==option.picLength-1&&option.goLast)option.goLast(option);
	}
	function showNext(){
		if(option.currentViewIndex<(option.picLength-1)){
			option.currentViewIndex+=1;
			changePics(option.currentViewIndex);
		}
	}
	function showPrev(){
		if(option.currentViewIndex>0){
			option.currentViewIndex-=1;
			changePics(option.currentViewIndex);
		}
	}
	function showBigPic(index){
		var viewHtml=option.floatPicTemp.replace(/{#previewLastId#}/g,'_previewLast').replace(/{#previewNextId#}/g,'_previewNext').replace(/{#floatViewId#}/g,'_viewPics').replace(/{#floatViewItemId#}/g,'_previewPicsItem').replace(/{#url#}/g,option.pics[option.currentViewIndex][option.floatViewArrayIndex]);
		var pl=option.picLength;
		var width=pl>1?650:550;
		var opt={
			width:width,
			height:550,
			title:'查看大图',
			html:viewHtml,
			cover:true,
			onClose:function(){			
				changePics(option.currentViewIndex);
				return true;
			}
		};
		option.bigPicView=$float(opt);
		var oImg=document.getElementById('_previewPicsItem');
		oImg.onclick=function(){		
			option.bigPicView.close();
		};
		if(pl>1){
			var oLast=document.getElementById('_previewLast');
			var oNext=document.getElementById('_previewNext');
			oLast.style.display="block";
			oNext.style.display="block";
			if(option.currentViewIndex==0){			
				oLast.style.color='#ccc';
			}else if(option.currentViewIndex==(pl-1)){			
				oNext.style.color='#ccc';
			};
			oLast.onclick=function(){
				if(option.currentViewIndex>0){
					var last=option.currentViewIndex-1;
					oImg.src=option.pics[last][option.floatViewArrayIndex];
					option.currentViewIndex=last;
					oNext.style.color='#2266bb';
					if(last==0){
						oLast.style.color='#ccc';
					};
				};
				return false;
			};
			oNext.onclick=function(){
				if(option.currentViewIndex<(pl-1)){
					var next=option.currentViewIndex+1;	
					oImg.src=option.pics[next][option.floatViewArrayIndex];
					option.currentViewIndex=next;
					oLast.style.color='#2266bb';
					if(next==(pl-1)){
						oNext.style.color='#ccc';
					}
				};
				return false;
			}
		}
	}
}

function $initScrollAd(){
	//活动卖场专用巨无霸组件，性能一般
	window._scollAd=$$("[tag='scrollAd']");
	if(_scollAd.length<1){
		return;
	}
	window._scollAd.each(function(){
		var n=0;
		var l=$$(this).find(".roll_pic li").length;
		var s='<ol class="roll_num">';
		for(var i=0;i<l;i++){
			s+='<li '+(i==n?'class="hover"':"")+' cindex="'+i+'">'+(i+1)+'</li>';
		}
		s+="</ol>";
		$$(this).append(s).attr("cindex","0").attr("autoScroll","true").attr("maxLength",l);
		$$(this).find(".roll_pic").css("left","-"+(n*parseInt($$(this).attr("rollWidth")))+"px");
		$$(this).find(".roll_num li").mouseover(function(){
			var p=$$(this).parent("ol").parent(".roll_ad");
			var i=$$(this).attr("cindex");
			var w=parseInt(p.attr("rollWidth"));
			p.attr("cindex",i)
			p.find(".roll_num li").removeClass("hover").filter(":eq("+i+")").addClass("hover")
			p.find(".roll_pic").stop().animate({left : -(i*w)},500);
		});
	}).mouseover(function(){
		$$(this).attr("autoScroll","false");
	}).mouseout(function(){
		$$(this).attr("autoScroll","true");
	});
	setInterval(function(){
		_scollAd.each(function(){
			if($$(this).attr("autoScroll")=="false"){
				return;
			}
			var i=parseInt($$(this).attr("cindex"));
			var m=parseInt($$(this).attr("maxLength"));
			var w=parseInt($$(this).attr("rollWidth"));
			var ni=i<(m-1)?(i+1):0
			$$(this).attr("cindex",ni);
			$$(this).find(".roll_num li").removeClass("hover").filter(":eq("+ni+")").addClass("hover");
			$$(this).find(".roll_pic").stop().animate({left : -(ni*w)},500)
		});
	},2000);
}

function $child(node,val,fn){
	var results=[],
		node=node||document.body;
		
	walk(node.firstChild,function(n){
		var actual=n.nodeType===1&&n.nodeName.toLowerCase();
		if(typeof actual === 'string' && (actual === val || typeof val !== 'string')){
				results.push(n);
				fn&&fn(n);
		}
	});
	
	return results;
			
	function walk(n,func){
		func(n);
		while(n=n.nextSibling){		
			func(n,func);			
		}
	}
}

function $checkUserIsVip(uin,callback){
	//检查用户是否会员，并把会员状态返回给回调函数
	$loadScript('http://ext.paipai.com/qqvip/is_vip?uin='+uin);
	//用户身份回调,参数:flag=1为会员，flag=0为非会员
	window.chkVipCallBack=callback;
}

function $htmlEncode(str){
    return typeof(str) != "string" ? "" : str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\"/g, "&quot;").replace(/ /g, "&nbsp;");
};

function $htmlDecode(str){
    return typeof(str) != "string" ? "" : str.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, "\"").replace(/&nbsp;/g, " ");
};

function $cataDrawList(o){
	/*
	//类目下拉选择菜单
	//20100720 create by homerhuang 
	*/
	var cataDrawItem = {
		drawItem:"drawCata",
		drawListItem:"drawCataList",
		formName:"searchForm",
		drawType:"0",		//下拉导航类型
		logValue:"1001",
		showType:"1",		//下拉菜单展示样式
		curSort:"",
		arrFirstSort:[],
		arrShopSort:[],
		arrMapSort:{},
		template:'<li class="{#cssName#}"><a attr="{#clsId#}" title="{#clsName#}" href="#h" lg="{#sLog#}" pos="{#sPos#}">{#clsName#}</a></li>',		//模版
		timerHandle:null,
		timeDelay:300,
		showClassList:function(){
			var tempArr = [[0,"所有分类"]],cataSelect = document.forms[cataDrawObj["formName"]].elements["sClassid"],tempSort;
			var cataItem = $id(cataDrawObj["drawListItem"]).getElementsByTagName("ul")[0],tempStr,tempNodes,tempHtml = "",len = 0,clsGroup = false;
			if (typeof(cataDrawObj["curSort"]) == "object"){
				tempSort = tempArr.concat(cataDrawObj["curSort"]);
				cataDrawObj["showType"] = 1;
			}else{
				tempSort = (cataDrawObj["drawType"] == 0)?cataDrawObj["arrFirstSort"]:cataDrawObj["arrShopSort"]
				cataDrawObj["showType"] = 2;
			}
			for (var n = 0; n < tempSort.length; n++){
				if (typeof(tempSort[n]) == "object"){
					tempStr = cataDrawObj["template"];
					if (cataDrawObj["showType"] == "1"){
						if (!clsGroup){
							tempStr = tempStr.replace("{#cssName#}","");
						}else{
							tempStr = tempStr.replace("{#cssName#}","c_bg");
						}
					}else{
						tempStr = tempStr.replace("{#cssName#}","s_" + len);
						len++;
					}
					tempStr = tempStr.replace("{#clsId#}",tempSort[n][0]);
					tempStr = tempStr.replace("{#sLog#}",cataDrawObj["logValue"]);
					tempStr = tempStr.replace("{#sPos#}",n);
					tempStr = tempStr.replace(/\{\#clsName\#\}/gi,tempSort[n][1]);
					tempHtml += tempStr;
				}else{
					if (tempSort[n] == 1){
						clsGroup = true;
					}else{
						clsGroup = false;
					}
				}
			}
			if (cataDrawObj["showType"] != "1"){cataItem.className = "all";}
			cataItem.innerHTML = tempHtml;
			tempNodes = cataItem.getElementsByTagName("a");
			for (var i = 0; i < tempNodes.length; i++){
				tempNodes[i].onclick = cataDrawObj.callFunction;
			}
		},
		callFunction:function(e){
			var event = e || window.event,srcEls;
			srcEls = event.target || event.srcElement;
			var cataSelect = document.forms[cataDrawObj["formName"]].elements["sClassid"],sfSelect = document.forms[cataDrawObj["formName"]].elements["sf"],sId = this.getAttribute("attr");
			cataSelect.value = sId;
			sfSelect.value = "77";
			if (cataDrawObj["drawType"] == 1){
				document.forms[cataDrawObj["formName"]].elements["shoptype"].value = cataDrawObj["arrMapSort"][sId]?cataDrawObj["arrMapSort"][sId]:0;
			}
			//$id(cataDrawObj["drawItem"]).innerHTML = this.getAttribute("title") + "<span></span>";
			$id(cataDrawObj["drawListItem"]).className = "h";
			$submitToSearch(cataDrawObj["formName"]);
		}
	};
	for (var n in o){cataDrawItem[n] = o[n]}
	window.cataDrawObj = cataDrawItem;
	//事件绑定
	$id(cataDrawObj["drawListItem"]).onmouseout = function(){
		$id(cataDrawObj["drawItem"]).setAttribute("attr",1);
		$id(cataDrawObj["drawItem"]).className = "";
		this.className = "h";
		var tempNode = $id(cataDrawObj["drawItem"]).getElementsByTagName("span")[0];
		tempNode.className = "";
	};
	$id(cataDrawObj["drawItem"]).onmouseout = function(){
		if (cataDrawObj["timerHandle"]){clearTimeout(cataDrawObj["timerHandle"]);}
		$id(cataDrawObj["drawListItem"]).className = "h";
		this.className = "";
		var tempNode = $id(cataDrawObj["drawItem"]).getElementsByTagName("span")[0];
		tempNode.className = "";
	};
	$id(cataDrawObj["drawItem"]).onmouseover = function(){
		if (this.getAttribute("attr") && this.getAttribute("attr") == 1){
			$id(cataDrawObj["drawListItem"]).className = "";
			this.className = "all";
			var tempNode = $id(cataDrawObj["drawItem"]).getElementsByTagName("span")[0];
			tempNode.className = "ex";
			this.setAttribute("attr",0);
		}else{
			cataDrawObj["timerHandle"] = setTimeout(function(){
				$id(cataDrawObj["drawListItem"]).className = "";
				$id(cataDrawObj["drawItem"]).className = "all";
				var tempNode = $id(cataDrawObj["drawItem"]).getElementsByTagName("span")[0];
				tempNode.className = "ex";
			},cataDrawObj["timeDelay"]);
		}
	};
	$id(cataDrawObj["drawListItem"]).onmouseover = function(){
		this.className = "";
		$id(cataDrawObj["drawItem"]).className = "all";
		var tempNode = $id(cataDrawObj["drawItem"]).getElementsByTagName("span")[0];
		tempNode.className = "ex";
	};
	cataDrawObj.showClassList();
	$id(cataDrawObj["drawListItem"]).onmousewheel = function(){return false};
};

function $changeType(o){
	/*
	//顶部搜索导航商品店铺切换Tab
	//20100720 create by homerhuang 
	*/
	var searchTypeItem = {
		tabName:"searchTab",		//切换按钮父节点
		tabItem:"p",				//切换按钮标签节点
		curTab:0,
		typeInpueName:"searchType",	//切换时保存对应搜索导航的input
		//点击是的切换函数
		changeFun:function(){		
			var t = this.getAttribute("attr");
			for (var n = 0; n < typeNodes.length; n++){
				if (n == t){
					typeNodes[n].className = "now";
					$id(searchTypeObj["typeInpueName"]).value = t;
				}else{
					typeNodes[n].className = "";
				}
			}
			searchTypeObj["evenFunc"](t);
		},
		//切换Tab的同时是否执行其他操作逻辑
		evenFunc:function(){
			var t = arguments[0];
			if (window["smartDrawObj"]){
				if (t == "0"){
					smartDrawObj["isAvai"] = true;
				}else{
					smartDrawObj["isAvai"] = false;
				}
			}
			if (window["cataDrawObj"]){
				cataDrawObj["drawType"] = t;
				cataDrawObj["showClassList"]();
			}
		}
	};
	for (var n in o){searchTypeItem[n] = o[n]}
	window.searchTypeObj = searchTypeItem;
	var typeTab = $id(searchTypeObj["tabName"]),typeItem;
	var typeNodes = typeTab.getElementsByTagName(searchTypeObj["tabItem"]);
	for (var i = 0; i < typeNodes.length; i++){
		typeNodes[i].setAttribute("attr",i);
		typeNodes[i].onclick = searchTypeObj["changeFun"];
		if (i == searchTypeObj["curTab"]){
			typeNodes[i].className = "now";
			$id(searchTypeObj["typeInpueName"]).value = searchTypeObj["curTab"];
		}else{
			typeNodes[i].className = "";
		}
	}
	if (searchTypeObj["curTab"] == "1" && window["cataDrawObj"]){
		if (window["smartDrawObj"]){smartDrawObj["isAvai"] = false;}
		cataDrawObj["drawType"] = searchTypeObj["curTab"];
		cataDrawObj["showClassList"]();
	}
};

function $decodeHtml(content){
	if(content == null){
		return "";	
	}
	return $strReplace(content, {
                    "&amp;" : '&',
		"&quot;" : '\"',
		"\\'" : '\'',
		"&lt;" : '<',
		"&gt;" : '>',
		"&nbsp;" : ' ',
		"&#39;" : '\'',
		"&#09;" : '\t',
		"&#40;" : '(',
     	"&#41;" : ')',
		"&#42;" : '*',
		"&#43;" : '+',
		"&#44;" : ',',
		"&#45;" : '-',
		"&#46;" : '.',
		"&#47;" : '/',
		"&#63;" : '?',
		"&#92;" : '\\',
		"<BR>" : '\n'
	});
};

function $getMp(n){
	var mp = $getCookie("mp");
    return mp?mp.split(":")[n]:"";
}

function $simpleValidator(){
	Validator = {
	Require : /.+/,
	Email : /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
	Phone : /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,11}(\-\d{1,6})?$/,
	Mobile : /^(852\d{8})|(((\(\d{2,3}\))|(\d{3}\-))?((13\d{9})|(14\d{9})|(15\d{9})|(18\d{9})))$/,
	Url : /^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/,
	IdCard : "this.IsIdCard(value)",	
	Currency : /^\d+(\.\d+)?$/,
	Number : /^\d+$/,
	Zip : /^[0-9]\d{5}$/,
	QQ : /^[1-9]\d{4,9}$/,
	Integer : /^[-\+]?\d+$/,
	Double : /^[-\+]?\d+(\.\d+)?$/,
	English : /^[A-Za-z]+$/,
	Chinese : /^[\u0391-\uFFE5]+$/,
	Username : /^[a-z]\w{3,}$/i,
	UnSafe : /^(([A-Z]*|[a-z]*|\d*|[-_\~!@#\$%\^&\*\.\(\)\[\]\{\}<>\?\\\/\'\"]*)|.{0,5})$|\s/,
	IsSafe : function(str){return !this.UnSafe.test(str);},
	SafeString : "this.IsSafe(value)",
	Filter : "this.DoFilter(value, getAttribute('accept'))",
	Limit : "this.limit(value.length,getAttribute('min'), getAttribute('max'))",
	LimitB : "this.limit(this.LenB(value), getAttribute('min'), getAttribute('max'))",
	LimitC : "this.limit(this.LenC(value), getAttribute('min'), getAttribute('max'))",
	Date : "this.IsDate(value, getAttribute('min'), getAttribute('format'))",
	Repeat : "value == document.getElementsByName(getAttribute('to'))[0].value",
	Range : "parseFloat(getAttribute('min')) <= parseFloat(value) && parseFloat(value) <= parseFloat(getAttribute('max'))",
	Compare : "this.compare(value,getAttribute('operator'),getAttribute('to'))",
	Custom : "this.Exec(value, getAttribute('regexp'))",
	Group : "this.MustChecked(getAttribute('name'), getAttribute('min'), getAttribute('max'))",
	ErrorItem : [document.forms[0]],
	ErrorMessage : ["温馨提示：由于以下可能原因，您需要调整输入信息。\t\t\t\t\n"],

	Validate : function(){
	var theForm;
		var mode;
		switch(arguments.length)
		{
			case 0:	
			 theForm = document.forms[0];
			 mode = 1;
			 break;
			case 1:
				if(typeof(arguments[0])=="object")
					theForm = arguments[0];
				else
					theForm = document.forms[arguments[0]];
				mode = 1;
				break;
			case 2:
			default:
				if(typeof(arguments[0])=="object")
					theForm = arguments[0];
				else
					theForm = document.forms[arguments[0]];
				mode = arguments[1];
				break;
		}

		var obj = theForm || event.srcElement;
		var count = obj.elements.length;
		this.ErrorMessage.length = 1;
		this.ErrorItem.length = 1;
		this.ErrorItem[0] = obj;
		var checkwithObject = null;
		for(var i=0;i<count;i++){
			with(obj.elements[i]){
				var _dataType = getAttribute("dataType");
				if(typeof(_dataType) == "object" || typeof(this[_dataType]) == "undefined")
						continue;
				this.ClearState(obj.elements[i]);
				if(getAttribute("checkwith")!=null)
				{
					var _theObj=getAttribute("checkwith");				
					var _unionObjs= document.getElementsByName(_theObj);
					var iIndex;
					if(_unionObjs.length > 0)
					{
						for(iIndex=0;iIndex<_unionObjs.length;iIndex++)
						{	
							if(value == ""&&_unionObjs[iIndex].value!="")
								break;	
						}
						if(iIndex <	_unionObjs.length) 
							continue;				
					}
				}
//alert(getAttribute("id"));
//alert(getAttribute("require"));
				if(getAttribute("require") == "false" && value == "")
					continue;
				
				switch(_dataType){
					case "IdCard" :
					case "Date" :
					case "Repeat" :
					case "Range" :
					case "Compare" :
					case "Custom" :
					case "Group" : 
					case "Limit" :
					case "LimitB" :
					case "LimitC" :
					case "SafeString" :
					case "Filter" :
					if(!eval(this[_dataType])) {
						this.AddError(i, getAttribute("msg"));
					}
					break;
					default :
					if(!this[_dataType].test(value)){
						this.AddError(i, getAttribute("msg"));
					}
					break;
			}
		}
	}
	
	if(this.ErrorMessage.length > 1){
		mode = mode || 1;
		var errCount = this.ErrorItem.length;
		switch(mode){
			case 2 :
				for(var i=1;i<errCount;i++)
				{
					this.ErrorItem[i].style.color = "red";
					this.ErrorItem[i].style.borderColor = "red";
				}
				case 1 :
					alert(this.ErrorMessage.join("\n"));
				try
				{
					this.ErrorItem[1].focus();
				}
				catch(bb){break;}
				break;
		case 3 :
				for(var i=1;i<errCount;i++){
					try{
					this.ErrorItem[i].style.borderColor = "red";
					var span = document.createElement("SPAN");
					span.id = "__ErrorMessagePanel";
					span.style.color = "red";					
					this.ErrorItem[i].parentNode.appendChild(span);
					span.innerHTML = this.ErrorMessage[i].replace(/\d+:/,"*");
					}
					catch(e){alert(e.description);}
				}
				this.ErrorItem[1].focus();
				break;
				default :
				alert(this.ErrorMessage.join("\n"));
				break;
			}
			return false;
		}
		return true;
	},

limit : function(len,min, max){
min = min || 0;
max = max || Number.MAX_VALUE;
return min <= len && len <= max;
},
LenB : function(str){
return str.replace(/[^\x00-\xff]/g,"**").length;
},
LenC : function(str){
	var exp = /^[A-Za-z0-9]+$/;
	if(!exp.test(str))
	{
		return 0;
	}
return str.replace(/[^\x00-\xff]/g,"**").length;
},
ClearState : function(elem){
with(elem){
style.color = "";
style.borderColor="";
var lastNode = parentNode.childNodes[parentNode.childNodes.length-1];
if(lastNode.id == "__ErrorMessagePanel")
parentNode.removeChild(lastNode);
}
},
AddError : function(index, str){
this.ErrorItem[this.ErrorItem.length] = this.ErrorItem[0].elements[index];
this.ErrorMessage[this.ErrorMessage.length] = this.ErrorMessage.length + ":" + str;
},
Exec : function(op, reg){
return new RegExp(reg,"g").test(op);
},
compare : function(op1,operator,op2){
switch (operator) {
case "NotEqual":
return (op1 != op2);
case "GreaterThan":
return (op1 > op2);
case "GreaterThanEqual":
return (op1 >= op2);
case "LessThan":
return (op1 < op2);
case "LessThanEqual":
return (op1 <= op2);
default:
return (op1 == op2); 
}
},
MustChecked : function(name, min, max){
var groups = document.getElementsByName(name);
var hasChecked = 0;
min = min || 1;
max = max || groups.length;
for(var i=groups.length-1;i>=0;i--)
if(groups[i].checked) hasChecked++;
return min <= hasChecked && hasChecked <= max;
},
DoFilter : function(input, filter){
	exp_str1 = filter.split(",").join("|");
	exp_str2 = exp_str1.replace(/\s+/g,"");
	return new RegExp("^.+\.(?=EXT)(EXT)$".replace(/EXT/g, exp_str2), "gi").test(input);
},
IsIdCard : function(number){
var date, Ai;
var verify = "10x98765432";
var verify2 = "10x98765432";
var Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
var area = ['','','','','','','','','','','','北京','天津','河北','山西','内蒙古','','','','','','辽宁','吉林','黑龙江','','','','','','','','上海','江苏','浙江','安微','福建','江西','山东','','','','河南','湖北','湖南','广东','广西','海南','','','','重庆','四川','贵州','云南','西藏','','','','','','','陕西','甘肃','青海','宁夏','新疆','','','','','','台湾','','','','','','','','','','香港','澳门','','','','','','','','','国外'];
var re = number.match(/^(\d{2})\d{4}(((\d{2})(\d{2})(\d{2})(\d{3}))|((\d{4})(\d{2})(\d{2})(\d{3}[x\d])))$/i);
if(re == null) return false;
if(re[1] >= area.length || area[re[1]] == "") return false;
if(re[2].length == 12){
Ai = number.substr(0, 17);
date = [re[9], re[10], re[11]].join("-");
}
else{
Ai = number.substr(0, 6) + "19" + number.substr(6);
date = ["19" + re[4], re[5], re[6]].join("-");
}
if(!this.IsDate(date, "ymd")) return false;
var sum = 0;
for(var i = 0;i<=16;i++){
sum += Ai.charAt(i) * Wi[i];
}
Ai +=verify.charAt(sum%11);
return (number.length ==15 || number.length == 18 && number.toLowerCase() == Ai);
},
IsDate : function(op, formatString)
{
formatString = formatString || "ymd";
var m, year, month, day;
switch(formatString){
case "ymd" :
m = op.match(new RegExp("^((\\d{4})|(\\d{2}))([-./])(\\d{1,2})\\4(\\d{1,2})$"));
if(m == null ) return false;
day = m[6];
month = m[5]*1;
year = (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3], 10));
break;
case "dmy" :
m = op.match(new RegExp("^(\\d{1,2})([-./])(\\d{1,2})\\2((\\d{4})|(\\d{2}))$"));
if(m == null ) return false;
day = m[1];
month = m[3]*1;
year = (m[5].length == 4) ? m[5] : GetFullYear(parseInt(m[6], 10));
break;
default :
break;
}
if(!parseInt(month)) return false;
month = month==0 ?12:month;
var date = new Date(year, month-1, day);
return (typeof(date) == "object" && year == date.getFullYear() && month == (date.getMonth()+1) && day == date.getDate());
function GetFullYear(y){return ((y<30 ? "20" : "19") + y)|0;}
}
}

return Validator

}

function setPath(){
	if(option.initValue){
		for(var i in regionMap){
			if(i.toString()===option.initValue.toString()){		//如果从省目录中找到就直接设置，不进行下一步操作
				option.provId=option.initValue;
				return;
			}else{	//当前省不是默认则找这个省的市数据，然后在进行下一步
				if (typeof(regionMap[i][2])=="object"){	//如果这个省有市的数据则在市数据中找
					var tempProv=i;
					for(var j in regionMap[i][2]){	
						if(j.toString()===option.initValue.toString()){	//在市数据中找到，就直接把这个省和市的数据写入设置中，并退出循环
							option.provId=tempProv;
							option.cityId=j;
							return;
						}else{//找地区数据
							var tempaeralist=regionMap[i][2][j][2];
							if(typeof(tempaeralist)=="object"){
								var tempCity=j;
								for(var k in tempaeralist){//在地区数据中找
									if (k.toString()===option.initValue.toString()){//找到
										option.provId=tempProv;
										option.cityId=tempCity;
										option.areaId=k;
										return;
									}
								}
							}
						}
					}
				}
			}
		}
	}
};

function fillProv(){
	var _theprovince=option.provinceHander
	if(_theprovince){
		if(_theprovince.options.length > 0) return;
		$addSelect(_theprovince,"","");
		for(var i in regionMap){
			$addSelect(_theprovince,regionMap[i][0],i);
		}
		if(option.provId){
			_theprovince.value = option.provId;
		}
	}
};

function fillCity(){
	var _thecity=option.cityHander;
	if(_thecity){
		if (!option.provId){return ;}
		var cityList=regionMap[option.provId][2];
/*		var hasIt = false;
		for(var j=0;j<_thecity.options.length;j++){
			if(_thecity.options[j].value.toString()==option.cityId && _thecity.options[j].value.toString()!=""){
				hasIt = true;
				break;
			}
		}
		if(hasIt){return;}*/
		_thecity.options.length = 0;
		$addSelect(_thecity,"","");
		for(var i in cityList){
			$addSelect(_thecity,cityList[i][0],i);
		}
		if(option.cityId){
			_thecity.value = option.cityId;
		}
	}
};


function fillArea(){
	var _thearea=option.areaHander;
	if(_thearea && option.area){
		var areaList;
		if(!option.cityId){
			_thearea[0].options.length = 0;
			return;
		}
		areaList=regionMap[option.provId][2][option.cityId][2];
		_thearea.options.length = 0;
		$addSelect(_thearea,"","");
		for(var i in areaList){
			$addSelect(_thearea,areaList[i][0],i);
		}
		if(option.areaId){
			_thearea.val(option.areaId)
		}
	}
};

function addListener(){
	
	function changeAction(){		
		vprovince=this.getAttribute("vprovince");
		vcity=this.getAttribute("vcity");
		varea=this.getAttribute("varea");
		var stype = this.getAttribute("stype");
		var thevalue = this.value;
		var thisselectvar = thevalue
		option.onSelect(this,stype);
		if(stype=="province" && thevalue==""){
 option.onSelectBlankProv(this);
			$id(vcity)?$id(vcity).options.length = 0:"";
			(varea && $id(varea))?$id(varea).options.length = 0:"";
		}
		if(stype=="city" && thevalue==""){
			option.onSelectBlankCity(this);
			thisselectvar=$id(vprovince).value;
		}
		
		option.provId="";
		option.cityId="";
		option.areaId="";
		option.initValue = thisselectvar;
		init();
	}
	if(option.cityHander){
		option.provinceHander.onchange="";
		option.provinceHander.onchange=changeAction;
	}
	if(option.areaHander){
		option.cityHander.onchange = "";
		option.cityHander.onchange = changeAction
	}
};

}

function $timeTipsStr(){
	var a="夜深了",b="早安",c="早上好",d="上午好",e="中午好",f="下午好",g="您好",h="晚上好";
	return [a,a,a,a,b,b,b,c,c,d,d,d,e,e,f,f,f,g,g,h,h,h,a,a][new Date().getHours()];
}

function $time33(str){
    //哈希time33算法
    for(var i = 0, len = str.length,hash = 5381; i < len; ++i){
       hash += (hash << 5) + str.charAt(i).charCodeAt();
    };
    return hash & 0x7fffffff;
};

function $selectColor(opt) {
	var option = {
		content : '',	//父元素id
		defaultColor : 'black',	//默认颜色
		colorTable: [
			["#FFFFFF", "#E5E4E4", "#D9D8D8", "#C0BDBD", "#A7A4A4", "#8E8A8B", "#827E7F", "#767173", "#5C585A", "#000000"], 
			["#FEFCDF", "#FEF4C4", "#FEED9B", "#FEE573", "#FFED43", "#F6CC0B", "#E0B800", "#C9A601", "#AD8E00", "#8C7301"], 
			["#FFDED3", "#FFC4B0", "#FF9D7D", "#FF7A4E", "#FF6600", "#E95D00", "#D15502", "#BA4B01", "#A44201", "#8D3901"], 
			["#E2F0FE", "#C7E2FE", "#ADD5FE", "#92C7FE", "#6EB5FF", "#48A2FF", "#2690FE", "#0162F4", "#013ADD", "#0021B0"], 
			["#D3FDFF", "#ACFAFD", "#7CFAFF", "#4AF7FE", "#1DE6FE", "#01DEFF", "#00CDEC", "#01B6DE", "#00A0C2", "#0084A0"], 
			["#EDFFCF", "#DFFEAA", "#D1FD88", "#BEFA5A", "#A8F32A", "#8FD80A", "#79C101", "#3FA701", "#307F00", "#156200"], 
			["#FFD2D0", "#FFBAB7", "#FE9A95", "#FF7A73", "#FF483F", "#FE2419", "#F10B00", "#D40A00", "#940000", "#6D201B"], 
			["#FFDAED", "#FFB7DC", "#FFA1D1", "#FF84C3", "#FF57AC", "#FD1289", "#EC0078", "#D6006D", "#BB005F", "#9B014F"], 
			["#FCD6FE", "#FBBCFF", "#F9A1FE", "#F784FE", "#F564FE", "#F546FF", "#F328FF", "#D801E5", "#C001CB", "#8F0197"], 
			["#D4C89F", "#DAAD88", "#C49578", "#C2877E", "#AC8295", "#C0A5C4", "#969AC2", "#92B7D7", "#80ADAF", "#9CA53B"]]
	}
	option = $extend(option, opt);
	window["PP_core_colorPanel_data"] = {curColor:option.defaultColor};
	var colorHtml = ['<div><div style="padding:2px;"><div tag="colorBanner" style="cursor:pointer;margin:2px 0px;display:block; height:15px;width:30px;background-Color:'+option.defaultColor+';"></div></div></div><div tag="colorPanel" style="display : none;position:absolute;"><table style="font-size:0px;">'], content = $id(option.content);
	for(var i = 0, len = option.colorTable.length; i < len; i++){
		var colorRow = option.colorTable[i];
		colorHtml.push('<tr>');
		for(var j = 0, cLen = colorRow.length; j < cLen; j++){
			colorHtml.push('<td color="'+colorRow[j]+'" style="border:1px solid white;cursor:pointer;width:15px;height:15px;background-color:'+colorRow[j]+'"></td>');
		}
		colorHtml.push('</tr>');
	}
	colorHtml.push('</table></div>');
	content.innerHTML = colorHtml.join('');
	var colorPanel = $attr('tag', "colorPanel", content)[0], colorBanner = $attr('tag', "colorBanner", content)[0];
	colorBanner.onclick = function(){
		clearTimeout(window["PP_core_colorPanel_data"].timeout);
		colorPanel.style.display = "block";
	}
	/* 颜色板移出 */
	colorPanel.onmouseout = function(e){
		var self = this;
		var e = e || window.event, src = e.target || e.srcElement, color = src.getAttribute('color');
		if(color){
			src.style.border = "1px solid white";
		}
		window["PP_core_colorPanel_data"].timeout = setTimeout(function(){
			self.style.display = "none";																 
		}, 500);		
	}
	/* 颜色版滑过 */
	colorPanel.onmousemove = function(e){
		clearTimeout(window["PP_core_colorPanel_data"].timeout);
		var e = e || window.event, src = e.target || e.srcElement, color = src.getAttribute('color');
		if(color){
			if(PP.miniIndex.isIE){
				src.style.border = "1px groove white";
			} else {
				src.style.border = "1px solid black";	
			}		
		}
	}
	/* 点击颜色版 */
	colorPanel.onclick = function(e){
		var e = e || window.event, src = e.target || e.srcElement, color = src.getAttribute('color');
		if(color){
			window["PP_core_colorPanel_data"].curColor = color;
			this.style.display = "none";
			colorBanner.style.backgroundColor = color;
		}
	}
	return {
		dispose : function(){
			$destoryDomEvents(colorPanel);
			colorBanner = colorPanel = null;
		}
	}
};

function $mouseouter(option){
    var opt={
        title:null,//dom
        content:null,//dom
        outFunc:function(){
            $addClass(opt.content,"h");
        },
        timer:100,
        intr:null
    };
    for(var k in option){
        opt[k]=option[k];
    };
    
    $mouseout(opt.title,outFunc);
    $mouseover(opt.content,overFunc);
    $mouseout(opt.content,outFunc);
    
    function overFunc(){
        clearTimeout(opt.intr);
        opt.intr = null;
    }
    
    function outFunc(){
        opt.intr=setTimeout(function(){
            opt.outFunc();
        },opt.timer);
    }    
}

function $keywordEditor(opt){
	//{ constKws: arrKey, begin: 0, remain: 200 - len }
	var option = {
		constArray : [],	//已经使用的关键词数组
//		begin : 0,	
		total : 200,
		remain : 200,		//剩余输入关键词个数
		usedTxt : null,		//正在使用个数文本
		remainTxt : null,	//剩余输入个数文本
		editObj : null,		//编辑框
		usedKws : {},		//正在使用的关键词
		constKws : {},		//已经使用过的关键词
		spliter: window.attachEvent ? '\r\n' : '\n', /* S 关键字编辑相关内容 */
		afterInput : function(){}
	}
	option = $extend(option, opt);
	//设置关键字可以输入的字数提示（去重）
	function setKWNum(l) {
		option.usedTxt.innerHTML = l;
		option.remainTxt.innerHTML = option.remain - l;
	};
	//整理输入框的文字，去掉空行和关键字前后的空格
	function refreshKWEdit() {
		var data = getNoEmptyData(true);
		option.editObj.value = data.text;
	};
	function refreshKWNum() {
		setKWNum(getNoEmptyData(false).arr.length);
		option.afterInput();
		//getCompareKeywordListFromMain();
	};
	//获取输入的关键词
	function getNoEmptyData(unique) {
		var rtn = {}, arr = (option.editObj.value.split('\n') || []), l = arr.length, i, newarr = [], key;
		//重新设置全局变量
		option.usedKws = {};
	
		for (i = 0; i < l; i++) {
			key = arr[i].replace(/(^\s*)|(\s*$)/g, '');
			if (key) {
				if (!unique || (!option.usedKws[key] && !option.constKws[key])) {	//增加一个对关键词列表内容的判断,不仅限于输入关键词的文本框
					newarr.push(key);
					option.usedKws[key] = 1;
				}
			}
		}
		//多于200个关键词的时候去掉200后的关键词
		var capacity = option.remain;
		if (newarr.length > capacity) {
			for (i = capacity; i < newarr.length; i++) {
				option.usedKws[newarr[i]] = 0;
			}
			newarr.length = capacity;
		}
		//设置关键字可以输入的字数提示
		setKWNum(newarr.length);
	
		if (newarr.length > 0) {
			rtn.text = (newarr.join(option.spliter) + option.spliter);
			rtn.arr = newarr;
		} else {
			rtn.text = '';
			rtn.arr = [];
		}
		return rtn;
	};
	
	//初始化关键字编辑器
	(function initKWEdit() {
		var _kw = option.editObj;
		var constKws = option["constKws"] || [];
		var l = option.constArray.length;
	
		if (!_kw) {
			return false;
		}
		_kw.oninput = refreshKWNum;
		_kw.onkeyup = refreshKWNum;
		_kw.onblur = function () {
			refreshKWEdit();
//			if (PP.express.getCompareKeywordListFromMain) {
//				PP.express.getCompareKeywordListFromMain();
//			}
		};
		refreshKWEdit();
		//记录已存在的关键字
		for (i = 0; i < l; i++) {
			option.constKws[option.constArray[i]] = 1;
		}
		//设置控件页面表现
		option.usedTxt.innerHTML = 0;
		option.remain = option.total - option.constArray.length;
		option.remainTxt.innerHTML = option.remain;
		//不可添加的情况下，禁用输入和保存按钮
//		if (option["remain"] == 0) {
//			$id('save_edit_btn').disabled = true;
//		};
		_kw = null;
	})();
	
	return {
		//添加关键词
		addKeyWord : function (kw) {
			//增加关键字
			var textarea_kw = option.editObj;
			if ($$.isArray(kw)) {
				var i, l = kw.length;
				for (i = 0; i < l; i++) {
					if (option.usedKws[kw[i]] || option.constKws[kw[i]]) {//已经存在此关键词
						continue;
					} else {
						option.usedKws[kw[i]] = 1;
						textarea_kw.value += (kw[i] + option.spliter);
					}
				}
				refreshKWNum();
				return true;
			} else {
				if (option.usedKws[kw] || option.constKws[kw]) {//已经存在此关键词
					return false;
				} else {
					option.usedKws[kw] = 1;
					textarea_kw.value += (kw + option.spliter);
					refreshKWNum();
					return true;
				}
			}
		}	
	}
};

/**
* 将时间字符串转为中文
* @str : 时间字符串
* @return : []
*/
$timeStrToReadable = function (str, showEmpty) {
    return timeArrToReadable($timeStrToArr(str));
    /**
    * 将时间数组翻译成内容
    *
    * @data ：时间数组
    * @return ：string
    */
    function timeArrToReadable(data) {
        var hc = [];
        var label = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"];
        if (!data || !data.length) {
            data = [];
            for (var i = 0, len = 7; i < len; i++) {
                data.push([]);
            };
        }
        for (var i = 0; i < data.length; i++) {
            var dayHs = [];
            var item = data[i];
            if (item.length > 0) {
                for (var j = 0; j < item.length; j++) {
                    //x.5或整数
                    var range = item[j];
                    var sh = parseInt(range.start);
                    var eh = parseInt(range.end);
                    dayHs.push('' + sh + (range.start > sh ? ':30' : ':00') + '-' + eh + (range.end > eh ? ':30' : ':00') + '');
                }
                hc.push(label[i] + '（' + dayHs.join(',') + '）');
            } else if (showEmpty) {
                hc.push(label[i]);
            }
        }
        return hc;
    }
};

function $timeStrToArr(str) {
        str = str ? str : '';
        //str = str.replace(/0*$/, '');
        var start = 0, end = 0;
        var hlist = [];
        for (var i = 0, len=7; i < len; i++) {
            hlist.push([]);
        };
    
        var curpos = 0;
        var hst = 0;
        var f = function(start, end) {
            start = ( (start - 1) % 48) / 2;
            end = ((end -1) % 48 + 1) / 2;
            var o = {'start': start, 'end': end};
            return o;
        }
        for(var i=0, len=str.length; i<len; i++) {
            var v = str.slice(i, i+1);
            if(v == 1 && start == 0 ) {
                start = end = i+1;
                continue;
            }
    
            if(v == 1 && start !=0 ) {
                end = i+1;
            }
             //终结一次: 遇到0 ， 最后一个数0, 逢48
            if((v == 0 && start !=0) || (i== (len-1) && start != 0) || ((i+1)%48 == 0 && start!=0) ) {
                //var pos = ((i+1)%48 == 0 && curpos<6) ? curpos - 1 : curpos;
                var pos = parseInt((start-1)/48);
                hlist[pos].push(f(start, end));
                start = 0, end=0;
                continue;
            }
        }
        // 最后一个数为1但是长度不为336的情况,
        if(start !=0) {
            var pos = parseInt((start-1)/48);
            hlist[pos].push(f(start, end));
        }
        return hlist;
    }


//type标识请求的方式,ls表loadscript，j132标识jquery，j126标识base，lk标识普通链接,fr标识form表单
function $addToken(url,type){
	var token=$getToken();
	//只支持http和https协议
	if(url=="" && url.indexOf("http")!=0){
		return url;
	}
	return token==""?url:url+(url.indexOf("?")!=-1?"&":"?")+"g_tk="+token+"&g_ty="+type;
}

function $setSelectedItem(name,selectedValue){
    //专门用于check和radio设置选择项，设置成功则返回true;
    var objs=document.getElementsByName(name),
        flag=false;
    for(var i=0,len=objs.length;i<len;i++){
        var t=objs[i];
        if(t.tagName.toLowerCase()=="input"){
            if((t.type.toLowerCase()=="checkbox" || t.type.toLowerCase()=="radio") ){    //设置单选复选框的值
                if(t.value==selectedValue){
                    t.checked=true;
                    flag=true;
                }
            }
        }
    };
    return flag;
};

function $name(name){
	return document.getElementsByName(name);
}

function $getToken(){
	var skey=$getCookie("skey"),
		token=skey==null?"":$time33(skey);
	return token;
}

/*		
“日历选择组件”的相关代码
--------------------------------------------
修订记录：
20100909 aidenli    录入legos平台
20100909 brianliu   迁移到新平台
20100420 brianliu	支持初始化设置时分
20100107 robinshen	
20081021 kpxu		创建本模块js框架
*/
//创建命名空间：PP.calendar
$namespace("PP.calendar");
///////////////需求描述定义区域//////////////////////////////////
//页面初始化的相关方法
function $calendar(opt) {
    var option = {
        it: null,
        zero: true,
        hour: '',
        showTime: false
    }
    option = $extend(option, opt);
    if (!option.showTime) {
        PP.calendar.easy(option.it, option.zero);
    } else {
        PP.calendar.easyLong(option.it, option.zero, option.hour);
    }
};
PP.calendar = function (opt) {
    var option = {
        input: "", //日历控件关联的表单,jquery语法
        action: "", //触发器的id列表，jquery语法
        float: true, //浮窗显示
        time: true, //使用时间
        format: "%y-%m-%d %h:%M", //格式化字符串
        x: 0,
        y: 0,
        //startYear: 2000, 	//起始年
        //endYear: 2010, 	//结束年
        defaultVar: '', //默认值
        haveZero: true, //是否补零
        autoXY: false, //每次点击时自动计算位置
        zeroHour: false, //是否从零点开始
        defaultHour: '00-00', //如果zeroHour为false，可以设置初始化的小时和分钟
        css: ''			//自定义css
    };
    $$.extend(option, opt);
    if ($$(option.input).length == 0) {
        return;
    }
	var thisYear = new Date().getFullYear();
	if(!option.startYear){
		option.startYear = thisYear-5;
	}
	if(!option.endYear){
		option.endYear = thisYear+1;
	}
    if (!$id("calendarFrame")) {
        try {
            $$("head").append("<style type='text/css'>.calender {width:170px;color:#000000	height:183px;font-size:12px;	margin-right:14px;background:url('') no-repeat right center #fff;border:1px solid #397EAE;padding:1px;}.calender ul,.calender li{list-style-type:none;margin:0;padding:0;}.day li,.date li{float:left;clear:none;}.calender .day {background-color:#EDF5FF;	height:20px;}.calender .day li,.calender .date li{float:left;width:14%;height:20px;line-height:20px;text-align:center}.calender li a {	text-decoration:none;font-family:Tahoma;font-size:11px;color:#333}.calender li a:hover{color:#f30;text-decoration:underline;}.calenderTitle a {text-decoration:none;margin:0 2px;color:#000;font-weight:bold}.today {background-color:#ffffaa;border:1px solid #f60;padding:2px}.today a {color:#f30;}.calenderBottom {clear:both;border-top:1px solid #ddd;padding: 3px 0;text-align:left}.calenderBottom a {text-decoration:none;margin:2px !important;font-weight:bold;color:#000;}.closeCalenderBox {	float:right;border:1px solid #000;background:#fff;font-size:9px;width:11px;height:11px;line-height:11px;text-align:center;overflow:hidden;font-weight:normal !important}</style>");
            //输出浮窗框架
            var cc = document.createElement('span');
            cc.style.position = 'absolute';
            cc.style.zIndex = 99999;
            cc.style.display = "none";
            cc.className = "calendarFrame";
            cc.id = "calendarFrame";
            cc.innerHTML = '<iframe width="165" height="170" frameborder="0" style="width:165px;height:170px;position:absolute;top:1px;left:1px;border:0;z-index:-100000;FILTER: Alpha(Opacity=110,Style=0)" ></iframe><div class="calender"><div class="calenderTitle" style="text-align:center;height:20px;line-height:20px;clear:both;"><A class="NextMonth" title="下一年" style="float:right;font-size:18px;" caction="nextYear">&raquo;</A><A class="LastMonth" title="上一年" style="float:left;font-size:18px;" caction="lastYear">&laquo;</A><A class="NextMonth" title="下一月" style="float:right;font-size:18px;" caction="nextMonth">&#8250;</A><A class="LastMonth" title="上一月" style="float:left;font-size:18px;" caction="lastMonth">&#8249;</A><span class="selectThisYear" faction="yearFrame"><A title="点击选择其他的年份" caction="years" ></A></span>年<span class="selectThisMonth" faction="monthFrame"><A title="点击选择其他的月份" caction="months"></A></span>月</div><div class="calenderBody" style="clear:both"><UL class="day"><LI style="clear:none;">日</LI><LI style="clear:none;">一</LI><LI style="clear:none;">二</LI><LI style="clear:none;">三</LI><LI style="clear:none;">四</LI><LI style="clear:none;">五</LI><LI style="clear:none;">六</LI></UL><UL class="date" faction="dayFrame"></UL></div><div class="calenderBottom" style="text-align:center;" ><A  style="float:right;" caction="close">×</A><span style="float:left;"><A title="回到今天的日期" caction="goToday" >今天</A></span><span faction="timeFrame"><span faction="hourFrame"><A title="点击选择其他的时间" caction="hours"></A></span>点<span faction="minuteFrame"><A title="点击选择其他的时间" caction="minutes"></A></span>分</span></div><div style="float:left;background-color:#ddd; text-align:center; line-height:20px;width:170px; height:20px;">点击日期 确认选择</div></div>';
            document.body.appendChild(cc);
            var cal = $$("#calendarFrame");
            //阻止冒泡
            cal.click(function (event) {
                if (event.preventDefault) {
                    event.preventDefault();
                    event.stopPropagation();
                } else {
                    event.cancelBubble = true;
                }
            }).find("[caction]").css("cursor", "pointer");
            cal.find("[caction='close']").add($$("body")).click(function () {
                $$("#calendarFrame").hide();
            });
            cal.find("[caction='nextMonth'],[caction='lastMonth'],[caction='nextYear'],[caction='lastYear'],[caction='goToday']").click(function () {
                PP.calendar.change(this, $$(this).attr("caction"));
            });
            //点击上一月、下一月、上一年、下一年、今天的事件
            cal.find("[faction='yearFrame'],[faction='monthFrame'],[faction='hourFrame'],[faction='minuteFrame']").each(function () {
                $$(this).attr("oldCode", $$(this).html());
            }).click(function () {
                if ($$(this).attr("select")) {
                    return;
                }
                PP.calendar.select(this);
            });
        } catch (e) { }
    }
    //阻止组件冒泡
    try {
        $$(option.input).add($$(option.action)).click(function (event) {
            if (event.preventDefault) {
                event.preventDefault();
                event.stopPropagation();
            } else {
                event.cancelBubble = true;
            }
        });
    } catch (e) { }
    var _input = $$(option.action);
    var _attr = option.float + "$" + option.time + "$" + option.format + "$" + $getX(_input.get(0)) + "$" + (parseInt($getY(_input.get(0))) + 5) + "$" + option.startYear + "$" + option.endYear + "$" + option.haveZero + "$" + option.autoXY + "$" + option.zeroHour + "$" + option.defaultHour;
    //绑定点击事件
    var _inputBox = $$(option.input)[0];
    _input.attr("_attr", _attr).click(function () {
        PP.calendar.init(_inputBox);
    });
};
///////////////功能代码定义区域//////////////////////////////////
//显示日历
PP.calendar.init = function (it) {
    var cal = $$("#calendarFrame");
    var _tempStr = it.value.split(' ')[0].split('-');
    var date;
    try {
        date = _tempStr.length == 3 ? new Date(_tempStr[0], parseInt(_tempStr[1]) - 1, _tempStr[2]) : new Date();
    } catch (e) {
        date = new Date();
    }
    var _attr = $$(it).attr("_attr").split("$");
    var _time = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + "-" + date.getHours() + "-" + date.getMinutes();
    if (_attr[9] == "true") {
        var _time = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + "-" + "00" + "-" + "00";
    } else if (_attr[10]) {
        //如果设置了默认时分
        var _time = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + "-" + _attr[10];
    }
    //显示日历
    cal.attr("_time", _time).attr("_attr", $$(it).attr("_attr")).attr("rid", it.id).show().css("left", $getX(it) + "px").css("top", (parseInt($getY(it)) + parseInt($$(it).height() + 5)) + "px");
    //是否显示时间
    if (_attr[1] == "true") {
        cal.find("[faction='timeFrame']").show();
    } else {
        cal.find("[faction='timeFrame']").hide();
    }
    //	if(_attr[9]=="true"){
    //		cal.find("[faction='timeFrame']").hide();
    //	}
    //初始化年，月
    PP.calendar.setTimeInfo(cal);
};
PP.calendar.easy = function (it, zero) {
    var _id = (typeof (it) == "object") ? it.id : it;
    var _it = $$("#" + _id).get();
    if (_it.length < 1) {
        return;
    }
    var opt = {
        input: "#" + _id,
        action: "#" + _id,
        format: "%y-%m-%d",
        //startYear: 2000,
        //endYear: 2010,
        time: false,
        autoXY: true,
        zeroHour: (zero ? true : false)
    };
    PP.calendar(opt);
};
PP.calendar.easyLong = function (it, zero, hour) {
    var _id = (typeof (it) == "object") ? it.id : it;
    var _it = $$("#" + _id).get();
    if (_it.length < 1) {
        return;
    }
    var opt = {
        input: "#" + _id,
        action: "#" + _id,
        format: "%y-%m-%d %h:%M",
        //startYear: 2000,
        //endYear: 2010,
        time: true,
        autoXY: true,
        zeroHour: (zero ? true : false),
        defaultHour: (hour ? hour : "00-00")
    };
    PP.calendar(opt);
};
//设置当前时间
PP.calendar.setTimeInfo = function (cal) {
    var _time = cal.attr("_time").split("-");
    cal.find("[caction='years']").html(_time[0].toString());
    cal.find("[caction='months']").html(_time[1].toString());
    cal.find("[caction='hours']").html(_time[3].toString());
    cal.find("[caction='minutes']").html(_time[4].toString());
    //生成当月的日历列表
    cal.find("[faction='dayFrame']").html(setDayList(cal)).attr("curState", _time[0] + "-" + _time[1]);
    cal.find("[cDays]").css("cursor", "pointer").click(function () {
        PP.calendar.selectDay(this);
    });
    function setDayList(cal) {
        var _time = cal.attr("_time").split("-");
        //以参数为当前日期
        var hc = "";
        //上个月的最后一天的日，如30,31,29
        var lDay = dateAdd("d", "-1", _time[0] + "-" + _time[1] + "-01").getDate();
        //上个月补齐天数：本月1号是星期几，那么上个月需要显示几天来补齐日期，灰色显示
        var lDays = getWeekDay(_time[0] + "-" + (_time[1] - 1) + "-01");
        //这个月最后一天
        var cDate = dateAdd("d", "-1", _time[0] + "-" + _time[1] + "-01");
        //这个月总天数
        var cDays = cDate.getDate();
        //下个月补齐天数：最后一天是星期几,如果最后一天不是星期天，那么输出的时候，就要用下个月的时间补齐6-n天
        var nDays = cDate.getDay();
        //今天的日期
        var todayObj = new Date();
        //今天的日期字符串
        today = todayObj.getFullYear() + "-" + todayObj.getMonth() + "-" + todayObj.getDate();
        //循环输出	上个月补齐的几天
        for (i = 0; i < lDays; i++) {  // Last Month's Date
            hc = "<LI style='color:#bbb;font-size:11px;clear:none;' >" + lDay + "</LI>" + hc;
            lDay--;
        }
        //循环输出这个月的日期
        for (i = 1; i <= cDays; i++) { // Current Month's Date
            //如果是今天的话就输出today样式
            //            if (today == _time[0] + "-" + (parseInt(_time[1]) - 1) + "-" + i) {
            if (_time[2] == i) {
                hc += "<li style='clear:none;' ><a href='javascript:;' class='today' cDays=" + i + " title='" + _time[0] + "-" + _time[1] + "-" + i + "'>" + i + "</a></li>";
            } else {
                hc += "<li style='clear:none;' ><a href='javascript:;' class='days' cDays=" + i + " title='" + _time[0] + "-" + _time[1] + "-" + i + "'>" + i + "</a></li>";
            }
        };
        //补齐最后一个星期的几天
        for (var i = 1; i < 7 - nDays; i++) {  // Next Month's Date
            hc += "<LI style='color:#bbb;font-size:11px;clear:none;'>" + i + "</LI>";
        }
        return hc;
    };
    //获取一某日是星期几，从0开始分别是（天，1，2，3，4，5，6）
    function getWeekDay(date) {
        var theDate;
        if (typeof (date) == "string") {
            theDate = new Date(date.split("-")[0], date.split("-")[1], date.split("-")[2]);
        }
        if (typeof (date) == "object") {
            theDate = date;
        }
        return theDate.getDay();
    };
    //日期运算，参数：单位,差值，基准日期
    function dateAdd(interval, number, date) {
        number = parseInt(number);
        //判断各种格式的日期初始值，如果有内容就直接赋值
        if (typeof (date) == "string") {
            var date = new Date(date.split("-")[0], date.split("-")[1], date.split("-")[2]);
        }
        if (typeof (date) == "object") {
            var date = date;
        }
        switch (interval) {
            case "y":
                return new Date(date.getFullYear() + number, date.getMonth(), date.getDate());
                break;
            case "m":
                return new Date(date.getFullYear(), date.getMonth() + number, checkLastDate(date.getFullYear(), date.getMonth() + number, date.getDate()));
                break;
            case "d":
                return new Date(date.getFullYear(), date.getMonth(), date.getDate() + number);
                break;
            case "w":
                return new Date(date.getFullYear(), date.getMonth(), 7 * number + date.getDate());
                break;
        };
    };
    //检查当月的最后一天是否正确，如果不正确就改成正确的
    function checkLastDate(year, month, date) {
        var enddate = ["31", "28", "31", "30", "31", "30", "31", "31", "30", "31", "30", "31"];
        var returnDate = "";
        enddate[1] = (year % 4 == 0) ? "29" : enddate[1];
        return (date > enddate[month]) ? enddate[month] : date;
    };
};
//修改当前日期，各种修改操作(修改对象，修改类型，目标数值)
PP.calendar.change = function (it, type, number) {
    var date = PP.calendar.getSelectedTime();
    var cal = $$("#calendarFrame");
    var _time = cal.attr("_time").split("-");
    date = new Date(_time[0], parseInt(_time[1]) - 1, _time[2], _time[3], _time[4]);
    if (type == "goToday") {
        date = new Date();
    }
    if (type == "nextYear") {
        date.setYear(date.getFullYear() + 1);
    }
    if (type == "lastYear") {
        date.setYear(date.getFullYear() - 1);
    }
    if (type == "nextMonth") {
        date.setMonth(date.getMonth() + 1);
    }
    if (type == "lastMonth") {
        date.setMonth(date.getMonth() - 1);
    }
    if (type == "yearFrame") {
        date.setYear(parseInt(number));
    }
    if (type == "monthFrame") {
        date.setMonth(parseInt(number) - 1);
    }
    if (type == "hourFrame") {
        date.setHours(parseInt(number));
    }
    if (type == "minuteFrame") {
        date.setMinutes(parseInt(number));
    }
    if (type == "day") {
        date.setDate(parseInt(number));
    }
    cal.attr("_time", date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + "-" + date.getHours() + "-" + date.getMinutes());
    //初始化年,月
    PP.calendar.setTimeInfo(cal);
};
//获取当前用户选择后的时间
PP.calendar.getSelectedTime = function () {
    var cal = $$("#calendarFrame");
    var _time = cal.attr("_time").split("-");
    return new Date(_time[0], parseInt(_time[1]) - 1, _time[2], _time[3], _time[4]);
};
//下拉框日期修改操作
PP.calendar.select = function (it) {
    var cal = $$("#calendarFrame");
    var time = cal.attr("_time").split("-");
    var attr = cal.attr("_attr").split("$");
    var type = $$(it).attr("faction");
    var _frame = [0, 0];
    var _value = "";
    if (type == "yearFrame") {
        _frame = [attr[5], attr[6]];
        _value = time[0];
    }
    if (type == "monthFrame") {
        _frame = [1, 12];
        _value = time[1];
    }
    if (type == "hourFrame") {
        _frame = [0, 23];
        _value = time[3];
    }
    if (type == "minuteFrame") {
        _frame = [0, 59];
        _value = time[4];
    }
    var hc = '<select>';
    for (var i = _frame[0]; i <= _frame[1]; i++) {
        hc += '<option value="' + i + '" >' + i + '</option>';
    };
    hc += '</select>';
    $$(it).attr("select", "on").html(hc).find("select").val(_value).change(function () {
        _parent = $$(this).parent();
        _parent.html(_parent.attr("oldCode")).removeAttr("select");
        PP.calendar.change(it, type, this.value);
    });
};
//选择日期
PP.calendar.selectDay = function (it) {
    var cal = $$("#calendarFrame");
    var attr = cal.attr("_attr").split("$");
    PP.calendar.change(it, "day", $$(it).attr("cDays"));
    var date = PP.calendar.getSelectedTime();
    var year = date.getFullYear().toString();
    var month = (date.getMonth() + 1).toString();
    var day = date.getDate().toString();
    var hour = date.getHours().toString();
    var minute = date.getMinutes().toString();
    //处理补零
    if (attr[7] == "true") {
        month = (month.length == 1) ? "0" + month : month;
        day = (day.length == 1) ? "0" + day : day;
        hour = (hour.length == 1) ? "0" + hour : hour;
        minute = (minute.length == 1) ? "0" + minute : minute;
    }
    var _value = attr[2];
    _value = _value.replace("%y", year);
    _value = _value.replace("%m", month);
    _value = _value.replace("%d", day);
    _value = _value.replace("%h", hour);
    _value = _value.replace("%M", minute);
    cal.find("[caction='close']").click();
    $$("#" + cal.attr("rid")).val(_value);
};

function $stopBubble(ev){
　　var evt = ev || window.event;
　　if (window.event) {// IE
　　　　evt.cancelBubble = true;
　　} else {// Firefox
　　　　evt.stopPropagation();
　　}
}

//添加tr的html代码
function $appendTR(tbody, html) {
    var div = document.createElement("DIV"), frag = document.createDocumentFragment();
    div.innerHTML = "<table><tbody>" + html + "</tbody></table>";
    var trAs = div.getElementsByTagName("TR"), len = trAs.length;
    if (len > 0) {
        for (var i = 0; i < len; i++) {
            frag.appendChild(trAs[i].cloneNode(true));
        }
    }
    tbody.appendChild(frag);
    div = null;
    return tbody;
};

//删除子节点
function $removeAllChild(obj) {
    for (var i = obj.childNodes.length - 1; i > -1; i--) {
        var child = obj.childNodes[i];
        obj.removeChild(child);
    }
    return obj;
};

/**
 * @desc: 显示form元素的验证结果。
 * @para: {Object} option: 1,dom:对应的消息显示的容器(一定是预先定义好的p元素);2,type:消息类型; 3,消息说明。
 */
function $showInputHint(option){
	option = $extend({
		dom:"",//必填。id, #id, dom, jqDom四种格式任选一
		type:"right",//必填。error, warn, right 三选一
		desc:"验证正确", //必填。状态的说明文字
		width: 100 //选填，默认100
	}, option);
	option.dom = $$(option.dom);
	option.dom.width((typeof option.width)=="string"?"auto":(option.width||100)).removeClass("msg-para-right msg-para-warn msg-para-error").addClass("msg-para-"+option.type).html('<span class="msg0-icon-'+ option.type +'"></span>' + option.desc);
	option.hide = function(){this.dom.hide();return this;}
	option.show = function(){this.dom.show();return this;}
	return option;
}

//绑定自动配置的rd统计
$bindAutoRd=function(oRd){
	for(var it in oRd){
        var o=$id(it);
        if(o!=null&&oRd[it]["rd"]!=""){
			var func=(function(rd){
							   return function(){
								   $countRd(rd);
								   }
						})(oRd[it]["rd"]);
            $addEvent(o,"click",func)
        }
    }
};

function $inpNum(oInput){
	$addEvent(oInput,"change",function(){
		oInput.value=oInput.value.replace(/^0|[^0-9]/g,"");
	});
	$addEvent(oInput,"keyup",function(e){
		e=window.event?window.event:e;
		var code = e.keyCode ? e.keyCode : e.which;
		if("8||46||35||36||37||38||39||40".indexOf(code)!=-1){
			return;
		}
		oInput.value=oInput.value.replace(/^0|[^0-9]/g,"");
	});
}

function $escHtmlEp(str){
/**
 * 用做过滤HTML标签里面的东东 比如这个例子里的<input value="XXX"> XXX就是要过滤的
 * @return {String}
 */	
	return str.replace(/[&'"<>\/\\\-\x00-\x1f\x80-\xff]/g, function(r){
		return "&#" + r.charCodeAt(0) + ";"
	});
};

function $escHtml(str){
/**
 * 用做过滤直接放到HTML里的
 * @return {String}
 */
	return str.replace(/[&'"<>\/\\\-\x00-\x09\x0b-\x0c\x1f\x80-\xff]/g, function(r){
		return "&#" + r.charCodeAt(0) + ";"
	}).replace(/ /g, "&nbsp;").replace(/\r\n/g, "<br />").replace(/\n/g,"<br />").replace(/\r/g,"<br />");
};

function $escScript(str){
/**
 * 用做过滤直接放到HTML里js中的
 * @return {String}
 */	
	return str.replace(/[\\"']/g, function(r){
		return "\\" + r;
	}).replace(/%/g, "\\x25").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\x01/g, "\\x01");
};

function $escUrl(str){
/**
 * 用做过滤直接URL参数里的 比如 http://show.qq.com/abc_cgi?a=XXX XXX就是要过滤的
 * @return {String}
 */
	return escape(str).replace(/\+/g, "%2B");
};

function $escMiniUrl(str){
/**
 * @return {String}
 */	
	return str.replace(/%/g, "%25");
};

function $escHrefScript(str){
/**
 * 用做过滤直接放到<a href="javascript:alert('XXX')">中的XXX
 * @return {String}
 */	
	return $escScript($escMiniUrl($escHtmlEp(str)));
};

function $escRegexp(str){
/**
 * 用做过滤直接放到正则表达式中的
 * @return {String}
 */	
	return str.replace(/[\\\^\$\*\+\?\{\}\.\(\)\[\]]/g, function(a){
		return "\\" + a;
	});
};

function $escNone(str){
/**
 * 空过滤，所有的都必须加上$esc，否则邮件会提醒
 * @return {String}
 */	
	return str+"";
}

function $setchkSelectedItem(objs,selectedValue){
//专门用于check设置选择项，设置成功则返回true;
var isExit = false;
     for(var i=0;i<objs.options.length;i++)
     {
         if(objs.options[i].value == selectedValue)
         {
             objs.options[i].selected = true;
             isExit = true;
             break;
         }
     } 
	return isExit;
};

function $backToTop(opt) {
	// 返回页面顶部
	
	// 预定义的代码
	var option = {
		id: "backToTop",			// 将要创建的回顶部按钮的 id 值
		className: "backToTop",		// 按钮的类名称，用于添加样式
		container: "foot",		// 容器id，用于定位按钮的参照物
		scroll: true,				// 是否在回顶时进行滑动，true 时启用滑动效果
		duration: 500,				// 滑动时长，毫秒
		fps: 50,					// 每秒滑动帧数
		cssUrl: "",					// 按钮所对应的外联样式表，会被内联样式覆盖掉
		
		//以下是内联样式
		background: "url('http://paipai.lady.qq.com/images/magazine6/totop_03.jpg') no-repeat scroll transparent",
		height : "67px",
		width : "19px",
		left: "960px",
		bottom : "10%"
	};
	
	// 合并参数
	$extend(option, opt);
	
	// 计算滑动的执行周期，毫秒
	option.periodical = Math.round(1000 / option.fps);
	// 步长总数，作为滑动的执行次数
	option.step = Math.round(option.duration / option.fps);
	
	// 创建按钮
	createButton(option.cssUrl);
	function createButton(cssUrl) {
		// 检测 id 是否已被其他元素使用，如果是就什么都不做直接返回
		if($id(option.id)) {
			return false;
		}
		
		// 异步加载css,如果 cssUrl 为空则不加载样式
        if (cssUrl){
            $loadCss(cssUrl);
        }
		
		// 创建元素
		var b = document.createElement("div");
		b.id = option.id;
		b.className = option.className;
		
		// 添加样式
		with(b.style) {
			background = option.background;
			display = "inline-block";
			position = "fixed";
			textIndent = "-999em";
			cursor = "pointer";
			height = option.height;
			width = option.width;
			left = "2000px";
			bottom = option.bottom;
		}
		//判断浏览器并锁定按钮水平位置
		$ready(function(){
			$isBrowser('ie6') && (b.style.position = "absolute");
			var ctX = $id(option.container) ? $getX($id(option.container)) : 0;
			b.style.left = ctX + parseInt(option.left) + "px";
			window.onresize = function() {
				var ctX = $id(option.container) ? $getX($id(option.container)) : 0;
				b.style.left = ctX + parseInt(option.left) + "px";
			}
		});		
		// 绑定点击事件
		b.onclick = backToTopHandle(option.scroll, option.step, option.periodical);
		document.body.appendChild(b);
	}
	
	// 点击响应，根据 scroll 的值返回不同的函数（有无滑动效果）
	function backToTopHandle(scroll, step, periodical) {
		if(scroll) {
			// timer 是记步器，用于跟总步数  step 比较，判断执行终点。pageHeight 记录鼠标点击时页面高度，以供记算每步滑动的距离。
			var timer = 0;
			var pageHeight;
			return function scrollPage() {
				// 启动滑动时先计算页面高度，滑动结束后记步器归零。
				if(timer === 0) {
					pageHeight = $getPageScrollHeight();
				}
				if (timer < step) {
					timer += 1;
					scrollStep(timer, pageHeight, -pageHeight, step);
					setTimeout(scrollPage, periodical);
				} else {
					timer = 0;
				}
			}
		} else {
			return function() {
				window.scrollTo(0, 0);
			}
		}
	}
	
	// 执行页面滑动，使用 easeOut 算法
	function scrollStep(timer, begin, target, step) {
		window.scrollTo(0, Math.ceil(-target *(timer/=step)*(timer-2) + begin));
	}
}

function $timer(opt){
    //定时器
    var option = {
        delay: 1000,//间隔时间
        act: "add",//添加或删除定时器   命令名：add、del
        func: function(){
        },//执行函数
        counter: 0,//计数器，每秒加1
        guid: 0//定时器唯一标识，创建定时器时返回，删除定时器时需要传入此值。
    };
    for (var k in opt) {
        option[k] = opt[k];
    }
    if (!window._pp_core_timer_) {
        window._pp_core_timer_list_ = {
            delay: 1000,
            count: 0,
            guid: 0
        };
        window._pp_core_timer_ = setInterval(function(){
            for (var key in window._pp_core_timer_list_) {
                var oTimer = window._pp_core_timer_list_[key];
                if (typeof(oTimer) == "object") {
                    oTimer.counter++;
                    if (oTimer.counter * window._pp_core_timer_list_.delay >= oTimer.delay) {
                        oTimer.counter = 0;
                        if (typeof(oTimer.func) == "function") {
                            oTimer.func();
                        }
                    }
                }
                oTimer = null;
            }
        }, window._pp_core_timer_list_.delay);
    }
    switch (option.act) {
    case 'add':
        option.guid = ++window._pp_core_timer_list_.guid;
        window._pp_core_timer_list_[option.guid] = option;
        window._pp_core_timer_list_.count++;
        return option;
    case 'del':
        if (option.guid && window._pp_core_timer_list_[option.guid]) {
            window._pp_core_timer_list_[option.guid] = null;
            delete window._pp_core_timer_list_[option.guid];
            window._pp_core_timer_list_.count--;
            if (window._pp_core_timer_list_.count <= 0) {
                clearInterval(window._pp_core_timer_);
                window._pp_core_timer_ = null;
            }
        }
        return option;
    }
}

function $commid2QQ(commid) {
    var s = commid;
    s = s.substring(0, 8);
    s = s.substring(2, 4) + s.substring(0, 2) + s.substring(6, 8) + s.substring(4, 6);
    s = s.substring(4, 8) + s.substring(0, 4)
    s = s.replace(/^0*/g, "")
    s = parseInt(s, 16)
    return s;
}

$scrollFix=function(id){}

function $getLocationMap(){
    return [7102, 7122, 7107, 7115, 7123, 7120, 7101, 7121, 7105, 7104, 7111, 7106, 7109, 7117, 7114, 5421, 5401, 5426, 5423, 5422, 6322, 6321, 6325, 6328, 6301, 5103, 5115, 5120, 5105, 5114, 5107, 5110, 5113, 5104, 5109, 5118, 5132, 5119, 5101, 5117, 5106, 5133, 5116, 5108, 5111, 5134, 4510, 4505, 4514, 4506, 4508, 4503, 4512, 4511, 4513, 4502, 4501, 4507, 4504, 4509, 3210, 3211, 3204, 3208, 3207, 3201, 3206, 3205, 3213, 3212, 3202, 3203, 3209, 2224, 2204, 2203, 2207, 2205, 2208, 2206, 2201, 2202, 3716, 3714, 3705, 3717, 3701, 3708, 3712, 3715, 3713, 3702, 3711, 3709, 3710, 3707, 3706, 3704, 3703, 3408, 3403, 3416, 3414, 3417, 3411, 3412, 3401, 3406, 3404, 3410, 3415, 3405, 3413, 3407, 3402, 3418, 1501, 1507, 1505, 1503, 1509, 1525, 1522, 1529, 1508, 1502, 1504, 1506, 1404, 1402, 1405, 1407, 1410, 1411, 1406, 1401, 1409, 1403, 1408, 4207, 4228, 4211, 4202, 4208, 4210, 4230, 4232, 4203, 4213, 4231, 4201, 4229, 4212, 4206, 4209, 4205, 1306, 1309, 1308, 1304, 1311, 1310, 1303, 1301, 1302, 1305, 1307, 3610, 3607, 3608, 3602, 3604, 3601, 3603, 3611, 3605, 3609, 3606, 3301, 3305, 3304, 3307, 3311, 3302, 3308, 3306, 3310, 3303, 3309, 6545, 6543, 6528, 6527, 6523, 6522, 6532, 6531, 6502, 6544, 6542, 6521, 6501, 6540, 6529, 3501, 3508, 3507, 3509, 3503, 3505, 3504, 3502, 3506, 6404, 6401, 6402, 6403, 5305, 5323, 5304, 5306, 5303, 5308, 5326, 5328, 5329, 5331, 5334, 5325, 5301, 5307, 5309, 5333, 2103, 2105, 2113, 2108, 2101, 2112, 2102, 2106, 2104, 2109, 2114, 2107, 2110, 2111, 6109, 6103, 6107, 6110, 6106, 6108, 6102, 6105, 6101, 6104, 5204, 5224, 5201, 5202, 5226, 5227, 5223, 5222, 5203, 2307, 2309, 2302, 2305, 2312, 2306, 2327, 2301, 2304, 2311, 2303, 2308, 2310, 4625, 4629, 4626, 4623, 4605, 4621, 4608, 4601, 4624, 4628, 4604, 4602, 4603, 4607, 4606, 4404, 4453, 4408, 4412, 4420, 4409, 4414, 4418, 4405, 4415, 4402, 4403, 4417, 4451, 4419, 4406, 4401, 4416, 4413, 4407, 4452, 4105, 4106, 4118, 4108, 4102, 4103, 4111, 4113, 4104, 4109, 4112, 4114, 4107, 4115, 4110, 4101, 4116, 4117, 6201, 6229, 6212, 6208, 6210, 6205, 6206, 6207, 6204, 6211, 6230, 6202, 6203, 6209, 4301, 4307, 4311, 4306, 4308, 4302, 4310, 4304, 4312, 4313, 4305, 4303, 4331, 4309, 9899, 7199, 5499, 6399, 5199, 4599, 3299, 2299, 3799, 3499, 1599, 1499, 4299, 1399, 3699, 3101, 3399, 8201, 6599, 3599, 1201, 1101, 6499, 5399, 2199, 6199, 5299, 8101, 2399, 4699, 4499, 5001, 4199, 6299, 4399, 9999]
}

function $arrayFind(arr,item){
	for (var i=0;i<arr.length;i++){
		if(arr[i]===item){
			return i;
		}
	};
	return -1;
}

function $xhrMaker(){
	var xhr;
	try{// Firefox, Opera 8.0+, Safari
		xhr=new XMLHttpRequest();
	}catch(e){//Internet Explorer
		try{
			xhr=new ActiveXObject("Msxml2.XMLHTTP");
		}catch(e){
			try {
				xhr=new ActiveXObject("Microsoft.XMLHTTP");
			}catch (e){
				xhr=null;
			}
		}
	};
	return xhr;
}

function $getServerTime(url) {
	var xhr=$xhrMaker(),url=url || "http://"+window.location.hostname;
	xhr.open("HEAD",url,false);
	xhr.send();
	return new Date(xhr.getResponseHeader("Date"));
}

function $picSlider(params){
		//显示浮窗,支持各种形态
		var inobj={
			slider:document.getElementById("slider"),	//	唯一id
			container:document.getElementById("container"),
			vertical:true, //是否垂直滑动，false则水平滑动
			count:5,
			auto:true,
			duration:30, //滑动持续时间
			change:0,
			time:10, //滑动延时
			pause:3000,
			index:0, // 当前索引
			images:[],
			onstart:function(o){return true;},//滑动开始事件
			onfinish:function(o){return true;},//滑动完成事件
			actionstyle:"Quart" //表示使用哪个tween算子 3个选项：Quart,Back,Bounce
		};
	    
		for(var i in params) inobj[i] = params[i];
		
		inobj._t = inobj._b = inobj._c = 0;//tween参数
		inobj.timer = null;
		
		inobj.slide = slide;
		inobj.move = move;
		inobj.moveto = moveto;
		inobj.next = next;
		inobj.previous = previous;
		
		inobj.Tween = {
			Quart: {
				easeOut: function(t,b,c,d){
					return -c * ((t=t/d-1)*t*t*t - 1) + b;
				}
			},
			Back: {
				easeOut: function(t,b,c,d,s){
					if (s == undefined) s = 1.70158;
					return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
				}
			},
			Bounce: {
				easeOut: function(t,b,c,d){
					if ((t/=d) < (1/2.75)) {
						return c*(7.5625*t*t) + b;
					} else if (t < (2/2.75)) {
						return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
					} else if (t < (2.5/2.75)) {
						return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
					} else {
						return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
					}
				}
			}
		}
		
		inobj.stop = stop;
		
		inobj._css = inobj.vertical ? "top" : "left";//方向
	
		//样式设置
		var p = getStyle(inobj.container).position;
		(p == "relative" || p == "absolute")?"":inobj.container.style.position = "relative";
		inobj.container.style.overflow = "hidden";
		inobj.slider.style.position = "absolute";
	
		inobj.change = inobj.change ? inobj.change : inobj.slider[inobj.vertical ? "offsetHeight" : "offsetWidth"] / inobj.count;
		
		if(inobj.count>1){
			var numUl = inobj.slider.nextSibling.nodeType==1?inobj.slider.nextSibling:inobj.slider.nextSibling.nextSibling;
			
			var nums=[];
			numUl.innerHTML = "";
			for(var i = 0; i < inobj.count; AddNum(i++)){};
		}
		
		
		function AddNum(i){
				var num = numUl.appendChild(document.createElement("a"));
				num.setAttribute("href",inobj.images[i].split("|")[1]);
				num.setAttribute("target","_blank");
				num.innerHTML = i+1;
				//num.innerHTML = '<a href="'++'" target="_blank">'+(i+1)+'</a>';
				num.onmouseover = function(){
					timer = setTimeout(function(){ num.className = "current";inobj.auto = false;inobj.slide(i); }, 200);
				}
				num.onmouseout = function(){ clearTimeout(inobj.timer); num.className = ""; inobj.auto = true; inobj.slide(); }
				nums[i] = num;
		}
		inobj.slide();
		
		
		
		
	
		return inobj;
	
		//开始切换
		function slide(index) {
			//修正index
			index == undefined && (index = inobj.index);
			index < 0 && (index = inobj.count - 1) || index >= inobj.count && (index = 0);
			//设置参数
			inobj.target = -Math.abs(inobj.change) * (inobj.index = index);
			inobj._t = 0;
			inobj._b = parseInt(getStyle(inobj.slider)[inobj.vertical ? "top" : "left"]);
			inobj._c = inobj.target - inobj._b;
			
			inobj.onstart(inobj);
			for(var j in nums){
				j==index?nums[j].className="current":nums[j].className="";
			}
			inobj.move();
		}
		
		//移动
	   function move() {
			clearTimeout(inobj.timer);
			//未到达目标继续移动否则进行下一次滑动
			if (inobj._c && inobj._t < inobj.duration) {
				inobj.moveto(Math.round(inobj.Tween[inobj.actionstyle].easeOut(inobj._t++, inobj._b, inobj._c, inobj.duration)));
				inobj.timer = setTimeout(inobj.move, inobj.time);
			}else{
				inobj.moveto(inobj.target);
				inobj.auto && (inobj.timer = setTimeout(inobj.next, inobj.pause));
			}
	   }
		
	
 	
	//移动到
	  function  moveto(i) {
		  if(!isNaN(i)){
		inobj.slider.style[inobj._css] = i + "px";
		  }
	  }
	  //下一个
	  function next() {
		inobj.slide(++inobj.index);
	  }
	  //上一个
	  function previous() {
		inobj.slide(--inobj.index);
	  }
	  //停止
	  function stop() {
		clearTimeout(inobj.timer); inobj.moveto(inobj.target);
	  }
	  
	  function getStyle(element){
			return element.currentStyle || document.defaultView.getComputedStyle(element, null);
	  }
  }

function $slider(obj){
    var opt={
        titleId:"",    			//tab标题的id
        titleTag:"",    		//tab的元素类型
        contentId:"",    		//内容的id    
        contentTag:"",    		//内容元素类型
		prevId:"",				//前一页
		nextId:"",				//下一页
		perView:1,				//每页显示个数
		className:"current",	//title选中的样式
		eventType:"mouseover",	//mouseover && click
        initIndex:NaN,			//初始化定位
        timeLag:300,			//启动延时，防止用户滑来滑去的情况
		funcInit:$empty(),		//初始化循环内容时候执行的函数
		funcTabInit:$empty(),	//初始化循环title时候执行的函数
		func:$empty(),			//当前元素显示时候执行的函数
		auto:false,				//是否自动轮播
		autoKeep:true,			//鼠标移开后继续轮播
		autoTimes:100,			//轮播次数
		autoLag:5000,			//自动轮播延时
		fadeLag:30,				//效果延时
		fadeTimes:300,			//效果要求执行时间，比如0.5s切换完成，而效果延时是0.1s，那么就是说五个步骤之后就执行完毕了
		initSpeed:100,			//初速度加成
		effect:'none',          //播放效果 'none','scrollx', 'scrolly', 'fade'
		width:0,				//内容区宽度
		height:0,				//内容区高度
		backAttr:"back_src",	//存储图片地址的属性		
		isLoadInit:true	,		//初始化的时候是否载入图片，当切换在屏幕不可见范围内进行的时候有用
		focusIndex:setEffect,	//提供给外部定位的接口
		clearAuto:function(){clearInterval(autoIntr)},//提供给外部的接口，清空轮播
		cont:null,				//内容列表
		tabs:null				//菜单列表
    };
	
    for(var i in obj){opt[i]=obj[i]};
	
	//自动获取的宽高不太准确，需要传入
	((opt.width==0 && opt.effect=="scrollx") || (opt.height==0 && opt.effect=="scrolly")) && (opt.effect="none");
	
	//if(!opt.titleId) debugger;		
    //遍历所有的标题和内容，并绑定事件
    var	total=0,		//统计数字
		autoCount=0,	//当前已播次数
		isInit=true,	//是否初始化进入; 
		intr=null,		//tab切换的interval
		autoIntr=null,	//自动切换的interval
		 _imgs=[];		//图片是否已经载入
	
	
	if(opt.contentId){
		//支持只有tab切换然后做别的事情的情况
		var oContent=$id(opt.contentId),
			_cont=$child(oContent,opt.contentTag,function(dom){
			//给内容的状态初始化
			switch(opt.effect){
				case "none":
					dom.style.display="none";
				break;
				case "scrollx":
					//考虑到动态加载图片的情况，区域的大小要限定
					dom.style.width=opt.width+"px";
					//如果效果为scrollx和fade，则全部向右漂移
					dom.style.styleFloat = dom.style.cssFloat = "left";
					dom.style.visibility = "hidden";
				break;			
				case "scrolly":
					//考虑到动态加载图片的情况，区域的大小要限定
					dom.style.height=opt.height+"px";
					dom.style.visibility = "hidden";
				break;
				case "fade":
					dom.style.display="none";
					dom.style.position="absolute";
					dom.style.left=0;
					dom.style.top=0;
				break;
			};
			//执行初始化函数
			opt.funcInit(total++,dom);
		});
		
		if(opt.auto){
			//循环播放进入和离开content的操作
			$addEvent(oContent,"mouseover",function(){
				clearInterval(autoIntr);
			});
			opt.autoKeep && $addEvent(oContent,"mouseout",function(){
				setAuto();
			});
		};		
		opt.cont=_cont;
	}
	
	//如果没有定义initIndex则随机
	var len=opt.perView,//下面多次用到，所以存储一下
		now=0;			//临时变量，当前显示的元素

	if(opt.titleId){
		//支持无titile切换
		var oTitle=$id(opt.titleId),
			_tabs=$child(oTitle,opt.titleTag,function(dom){
				opt.funcTabInit(now,dom);		
				dom.setAttribute("index",now++);
			});
		
		$addEvent(oTitle,opt.eventType,function(e){
			var tar=$getTarget(e,oTitle,opt.titleTag);
			if(tar){
				//放置current还没有设置为cur，然后鼠标又触发的状况
				//setClass在current=cur之前
				var cur=tar.getAttribute("index")*1;
				clearInterval(autoIntr);
				if(cur!=current&&tar.className!=opt.className){
					intr=setTimeout(function(){
						setEffect(cur);						
					},opt.timeLag);		
				}	
			}
		});

		$addEvent(oTitle,"mouseout",function(e){
			var tar=$getTarget(e,oTitle,opt.titleTag);
			if(tar){
				//clearInterval(autoIntr);
				clearTimeout(intr);
				opt.auto && opt.autoKeep && setAuto();	
			}
		});	
		opt.tabs=_tabs;
		total=now;
	};
	
	var	pageTotal=Math.ceil(total/len),	//分页
		current=isNaN(opt.initIndex)?$randomInt(pageTotal):opt.initIndex,		
		autoTotal=opt.autoTimes * total - 1; //总共轮播次数;
		
	
	//默认展示配置项目
	setEffect(current);
	
	//判断是否自动切换
	opt.auto && setAuto();
	
	//绑定上一个、下一个的点击
	opt.prevId && (
		$id(opt.prevId).onclick=function(){
			clearInterval(autoIntr);
			setEffect((now=current-1)<0?(pageTotal-1):now);
		}
	);
	
	opt.nextId && (
		$id(opt.nextId).onclick=function(){
			clearInterval(autoIntr);
			setEffect((now=current+1)>=pageTotal?0:now);
		}
	)	
	
	//初始化结束
	isInit=false;
	
	return opt;

	//自动切换设置
	function setAuto(){
		autoIntr=setInterval(function(){
			if(autoCount>=autoTotal){
				clearInterval(autoIntr);
			}else{
				setEffect((now=current+1)>=pageTotal?0:now);
				autoCount++;	
			}
		},opt.autoLag);	
	}
		
	//设置特效
	function setEffect(cur){
		//if(opt.isLoadInit==false) debugger;
		if(!opt.contentId){
			//如果没有contentId，简单解决
			showItem(cur);
			current=cur;
			return;
		};
		if(isInit){
			//初始化动态效果
			switch(opt.effect){
				case "scrollx":
					oContent.style.position="relative";
					oContent.style.width=total * opt.width +"px";
					oContent.style.left=-current*opt.width+"px";
				break;
				case "scrolly":
					oContent.style.position="relative";
					oContent.style.top=-current*opt.height+"px";
				break;
				case "fade":
					oContent.style.position="relative";
				break;
			};
			for(var i=0;i<len;i++){
				(now = cur+i) < total && showItem(now);
			};
			current=cur;	
		}else{
			//传入来之前应确保cur!=curren，否则会被当作是初始化
			var fadeStep=Math.floor(opt.fadeTimes/opt.fadeLag),	//计算效果步骤
				fadeIntr=null,
				fadeCount=0;
			opt.titleId && $delClass(_tabs[current],opt.className);
			switch(opt.effect){
				case "none":
					//if(len>1) debugger;
					for(var i=0;i<len;i++){
						(now = current*len+i) < total && (_cont[now].style.display="none");
						(now = cur*len+i) < total && showItem(now);
					};
					current=cur;
				break;
				case "scrollx":					
					var left=getSpeed(opt.width);
					showItem(cur);
					fadeIntr=setInterval(function(){	
						//debugger;		
						if(fadeCount++>=fadeStep){
							clearInterval(fadeIntr);
							//下面的二次确认应该不太必要了
							//oContent.style.left=-endLeft+"px";
							current=cur;
						}else{	
							oContent.style.left=-getMove(left)+"px";
						};						
					},opt.fadeLag);
				break;
				case "scrolly":
					//debugger;
					var top=getSpeed(opt.height);
					showItem(cur);	
					fadeIntr=setInterval(function(){	
						//debugger;		
						if(fadeCount++>=fadeStep){
							clearInterval(fadeIntr);
							//oContent.style.top=-endTop+"px";
							current=cur;						
						}else{	
							oContent.style.top=-getMove(top)+"px";
						};						
					},opt.fadeLag);	
				break;
				case "fade":
					showItem(cur);
					fadeIntr=setInterval(function(){	
						//if(!opt.titleId) debugger;		
						if(fadeCount++>=fadeStep){
							clearInterval(fadeIntr);
							//oContent.style.top=-endTop+"px";
							//如果不加zIndex问题，某些情况下会有问题，例如title提示
							_cont[current].style.zIndex=0;
							_cont[cur].style.zIndex=1;	
							current=cur;					
						}else{
							var per=fadeCount/fadeStep;
														
							_cont[current].style.filter="alpha(opacity="+(1-per)*100+")";
							//_cont[current].style.MozOpacity=1-per;
							_cont[current].style.opacity=1-per;		
							
							_cont[cur].style.filter="alpha(opacity="+(per*100)+")";
							//_cont[cur].style.MozOpacity=per;
							_cont[cur].style.opacity=per;		
						};						
					},opt.fadeLag);
				break;
			};						
		}
		
		function getSpeed(s){
			//匀速减速运动公式S=vt-at^2,减速到0，即S为最终距离，s为当前距离,
			var v=Math.ceil(s/fadeStep) + opt.initSpeed,	//给一个初始速度
				a=(v*fadeStep-s)/fadeStep/fadeStep,		//计算加速度
				flag=(cur - current)<0?-1:1,
				end=cur*s,
				here=(cur - flag)*s,//直接定位到它的前一个
				oFirst=_cont[0];
			current == 0 && (oFirst.style.position="static");
			if(current + 1 == total && cur == 0){
				//如果是最后一个到第一个情况，仍然保持向左侧滑动
				flag = 1;
				end=(current+1)*s;
				here=current*s;
				oFirst.style.position="relative";
				opt.effect=="scrollx"?oFirst.style.left=end + "px":oFirst.style.top=end + "px";
			};						
			return {
				a:a,
				v:v,
				flag:flag,
				end:end,
				here:here
			}
		}
		
		function getMove(obj){
			var move=obj.here + obj.flag*(obj.v-obj.a*fadeCount)*fadeCount;
			//判断不要拉过头了
			if((obj.flag>0 && move>obj.end) || (obj.flag<0 && move<obj.end)){
				move=obj.end;
				fadeCount=fadeStep;
			};			
			return move;
		}
				
		function showItem(cur){
			//设定当前元素的状态
			//if(opt.effect=="none") debugger;
			//设置title的样式，并将滚动到的地方设置为当前
			//如果当前是隐藏的，先显示出来
			if(opt.contentId && !_imgs[cur] && (isInit==false || (isInit==true && opt.isLoadInit==true))){
				//并不能确保分页的最后一页数量为len && 如果图片未载入，并且不是初始化或是初始化且需要加载
				$loadImg(_cont[cur],opt.backAttr);
				_imgs[cur]=true;
			};
			if(opt.contentId){		
				_cont[cur].style.display=="none" && (_cont[cur].style.display="block");
				_cont[cur].style.visibility=="hidden" && (_cont[cur].style.visibility="visible");		
			};
			if(opt.titleId){
				$addClass(_tabs[cur],opt.className);	
				_tabs[cur].style.display=="none" && (_tabs[cur].style.display="block");
			};
			opt.func(cur);	
		}
	}
};

function $loadImg(obj,attr){
	//载入隐藏的图片
	var attr=attr || "back_src",
		images = obj.getElementsByTagName("IMG");
	for(var i=0,len=images.length;i<len;i++){
		var oImg=images[i],
			src=oImg.getAttribute(attr);
		''==oImg.src && src && (oImg.src=src);
	}
}

function $setHtml(o,html){
	if(o&&o.nodeType==1){
		o.innerHTML=$escNone(html);
	}
}

function $focus(dom,word){
	var val=dom.value,
		len=val.length;
	$ready(function(){	dom.focus()});			
	if(len==0) return;//如果textarea里面没有数据，直接focus即可。

	if(word){
		var start=val.indexOf(word);
		if(document.createRange){
			//firefox
			dom.setSelectionRange(start,start+word.length);
		}else{
			var r = dom.createTextRange();
			r.findText(word);
			r.select();
		}
	}else if(word===""){
		dom.select();
	}else if(word===0){
		if(document.createRange){
			dom.setSelectionRange(0,0);
		};
	}else{
		if(document.createRange){
			dom.setSelectionRange(len,len);	
		}else{
			var r = dom.createTextRange();
			r.move('character',len);
			r.select();
		};		
	};

};

function $initExpLocationObj() {
    (function () {
        /*地区数组*/
        var _a = {};
        _a[0] = '请选择';
        _a[11] = 'B 北京';
        _a[21] = 'L 辽宁',
		_a[31] = 'S 上海';
        _a[44] = 'G 广东';
        _a[34] = 'A 安徽';
        _a[50] = 'C 重庆';
        _a[35] = 'F 福建';
        _a[46] = 'H 海南';
        _a[13] = 'H 河北';
        _a[41] = 'H 河南';
        _a[23] = 'H 黑龙江';
        _a[42] = 'H 湖北';
        _a[43] = 'H 湖南';
        _a[62] = 'G 甘肃';
        _a[45] = 'G 广西';
        _a[52] = 'G 贵州';
        _a[22] = 'J 吉林';
        _a[36] = 'J 江西';
        _a[32] = 'J 江苏';
        _a[15] = 'L 内蒙古';
        _a[64] = 'N 宁夏';
        _a[63] = 'Q 青海';
        _a[37] = 'S 山东';
        _a[14] = 'S 山西';
        _a[61] = 'S 陕西';
        _a[51] = 'S 四川';
        _a[12] = 'T 天津';
        _a[54] = 'X 西藏';
        _a[65] = 'X 新疆';
        _a[53] = 'Y 云南';
        _a[33] = 'Z 浙江';
        _a[71] = 'T 台湾';
        _a[81] = 'X 香港';
        _a[82] = 'A 澳门';
        _a[98] = 'Z 中国未识别地区';
        _a[99] = 'G 国外';

        var _sa = {};
        _sa[0] = {};
        _sa[11] = {};
        _sa[12] = {};
        _sa[13] = {};
        _sa[14] = {};
        _sa[15] = {};
        _sa[21] = {};
        _sa[22] = {};
        _sa[23] = {};
        _sa[31] = {};
        _sa[32] = {};
        _sa[33] = {};
        _sa[34] = {};
        _sa[35] = {};
        _sa[36] = {};
        _sa[37] = {};
        _sa[41] = {};
        _sa[42] = {};
        _sa[43] = {};
        _sa[44] = {};
        _sa[45] = {};
        _sa[46] = {};
        _sa[50] = {};
        _sa[51] = {};
        _sa[52] = {};
        _sa[53] = {};
        _sa[54] = {};
        _sa[61] = {};
        _sa[62] = {};
        _sa[63] = {};
        _sa[64] = {};
        _sa[65] = {};
        _sa[71] = {};
        _sa[81] = {};
        _sa[82] = {};
        _sa[98] = {};
        _sa[99] = {};

        _sa[0][0] = '请选择';
        _sa[11][1100] = '请选择';
        //省市增加 XX01
        _sa[11][1101] = '北京';

        _sa[12][1200] = '请选择';
        _sa[12][1201] = '天津';

        _sa[13][1300] = '请选择';
        _sa[13][1301] = '石家庄';
        _sa[13][1302] = '唐山';
        _sa[13][1303] = '秦皇岛';
        _sa[13][1304] = '邯郸';
        _sa[13][1305] = '邢台';
        _sa[13][1306] = '保定';
        _sa[13][1307] = '张家口';
        _sa[13][1308] = '承德';
        _sa[13][1309] = '沧州';
        _sa[13][1310] = '廊坊';
        _sa[13][1311] = '衡水';
        _sa[13][1399] = '未识别地区';

        _sa[14][1400] = '请选择';
        _sa[14][1401] = '太原';
        _sa[14][1402] = '大同';
        _sa[14][1403] = '阳泉';
        _sa[14][1404] = '长治';
        _sa[14][1405] = '晋城';
        _sa[14][1406] = '朔州';
        _sa[14][1407] = '晋中';
        _sa[14][1408] = '运城';
        _sa[14][1409] = '忻州';
        _sa[14][1410] = '临汾';
        _sa[14][1411] = '吕梁';
        _sa[14][1499] = '未识别地区';

        _sa[15][1500] = '请选择';
        _sa[15][1501] = '呼和浩特';
        _sa[15][1502] = '包头';
        _sa[15][1503] = '乌海';
        _sa[15][1504] = '赤峰';
        _sa[15][1505] = '通辽';
        _sa[15][1506] = '鄂尔多斯';
        _sa[15][1507] = '呼伦贝尔';
        _sa[15][1508] = '巴彦淖尔';
        _sa[15][1509] = '乌兰察布';
        _sa[15][1522] = '兴安';
        _sa[15][1525] = '锡林郭勒';
        _sa[15][1529] = '阿拉善';
        _sa[15][1599] = '未识别地区';

        _sa[21][2100] = '请选择';
        _sa[21][2101] = '沈阳';
        _sa[21][2102] = '大连';
        _sa[21][2103] = '鞍山';
        _sa[21][2104] = '抚顺';
        _sa[21][2105] = '本溪';
        _sa[21][2106] = '丹东';
        _sa[21][2107] = '锦州';
        _sa[21][2108] = '营口';
        _sa[21][2109] = '阜新';
        _sa[21][2110] = '辽阳';
        _sa[21][2111] = '盘锦';
        _sa[21][2112] = '铁岭';
        _sa[21][2113] = '朝阳';
        _sa[21][2114] = '葫芦岛';
        _sa[21][2199] = '未识别地区';

        _sa[22][2200] = '请选择';
        _sa[22][2201] = '长春';
        _sa[22][2202] = '吉林';
        _sa[22][2203] = '四平';
        _sa[22][2204] = '辽源';
        _sa[22][2205] = '通化';
        _sa[22][2206] = '白山';
        _sa[22][2207] = '松原';
        _sa[22][2208] = '白城';
        _sa[22][2224] = '延边';
        _sa[22][2299] = '未识别地区';

        _sa[23][2300] = '请选择';
        _sa[23][2301] = '哈尔滨';
        _sa[23][2302] = '齐齐哈尔';
        _sa[23][2303] = '鸡西';
        _sa[23][2304] = '鹤岗';
        _sa[23][2305] = '双鸭山';
        _sa[23][2306] = '大庆';
        _sa[23][2307] = '伊春';
        _sa[23][2308] = '佳木斯';
        _sa[23][2309] = '七台河';
        _sa[23][2310] = '牡丹江';
        _sa[23][2311] = '黑河';
        _sa[23][2312] = '绥化';
        _sa[23][2327] = '大兴安岭';
        _sa[23][2399] = '未识别地区';

        _sa[31][3100] = '请选择';
        _sa[31][3101] = '上海';

        _sa[32][3200] = '请选择';
        _sa[32][3201] = '南京';
        _sa[32][3202] = '无锡';
        _sa[32][3203] = '徐州';
        _sa[32][3204] = '常州';
        _sa[32][3205] = '苏州';
        _sa[32][3206] = '南通';
        _sa[32][3207] = '连云港';
        _sa[32][3208] = '淮安';
        _sa[32][3209] = '盐城';
        _sa[32][3210] = '扬州';
        _sa[32][3211] = '镇江';
        _sa[32][3212] = '泰州';
        _sa[32][3213] = '宿迁';
        _sa[32][3299] = '未识别地区';

        _sa[33][3300] = '请选择';
        _sa[33][3301] = '杭州';
        _sa[33][3302] = '宁波';
        _sa[33][3303] = '温州';
        _sa[33][3304] = '嘉兴';
        _sa[33][3305] = '湖州';
        _sa[33][3306] = '绍兴';
        _sa[33][3307] = '金华';
        _sa[33][3308] = '衢州';
        _sa[33][3309] = '舟山';
        _sa[33][3310] = '台州';
        _sa[33][3311] = '丽水';
        _sa[33][3399] = '未识别地区';

        _sa[34][3400] = '请选择';
        _sa[34][3401] = '合肥';
        _sa[34][3402] = '芜湖';
        _sa[34][3403] = '蚌埠';
        _sa[34][3404] = '淮南';
        _sa[34][3405] = '马鞍山';
        _sa[34][3406] = '淮北';
        _sa[34][3407] = '铜陵';
        _sa[34][3408] = '安庆';
        _sa[34][3410] = '黄山';
        _sa[34][3411] = '滁州';
        _sa[34][3412] = '阜阳';
        _sa[34][3413] = '宿州';
        _sa[34][3414] = '巢湖';
        _sa[34][3415] = '六安';
        _sa[34][3416] = '亳州';
        _sa[34][3417] = '池州';
        _sa[34][3418] = '宣城';
        _sa[34][3499] = '未识别地区';

        _sa[35][3500] = '请选择';
        _sa[35][3501] = '福州';
        _sa[35][3502] = '厦门';
        _sa[35][3503] = '莆田';
        _sa[35][3504] = '三明';
        _sa[35][3505] = '泉州';
        _sa[35][3506] = '漳州';
        _sa[35][3507] = '南平';
        _sa[35][3508] = '龙岩';
        _sa[35][3509] = '宁德';
        _sa[35][3599] = '未识别地区';

        _sa[36][3600] = '请选择';
        _sa[36][3601] = '南昌';
        _sa[36][3602] = '景德镇';
        _sa[36][3603] = '萍乡';
        _sa[36][3604] = '九江';
        _sa[36][3605] = '新余';
        _sa[36][3606] = '鹰潭';
        _sa[36][3607] = '赣州';
        _sa[36][3608] = '吉安';
        _sa[36][3609] = '宜春';
        _sa[36][3610] = '抚州';
        _sa[36][3611] = '上饶';
        _sa[36][3699] = '未识别地区';

        _sa[37][3700] = '请选择';
        _sa[37][3701] = '济南';
        _sa[37][3702] = '青岛';
        _sa[37][3703] = '淄博';
        _sa[37][3704] = '枣庄';
        _sa[37][3705] = '东营';
        _sa[37][3706] = '烟台';
        _sa[37][3707] = '潍坊';
        _sa[37][3708] = '济宁';
        _sa[37][3709] = '泰安';
        _sa[37][3710] = '威海';
        _sa[37][3711] = '日照';
        _sa[37][3712] = '莱芜';
        _sa[37][3713] = '临沂';
        _sa[37][3714] = '德州';
        _sa[37][3715] = '聊城';
        _sa[37][3716] = '滨州';
        _sa[37][3717] = '菏泽';
        _sa[37][3799] = '未识别地区';

        _sa[41][4100] = '请选择';
        _sa[41][4101] = '郑州';
        _sa[41][4102] = '开封';
        _sa[41][4103] = '洛阳';
        _sa[41][4104] = '平顶山';
        _sa[41][4105] = '安阳';
        _sa[41][4106] = '鹤壁';
        _sa[41][4107] = '新乡';
        _sa[41][4108] = '焦作';
        _sa[41][4109] = '濮阳';
        _sa[41][4110] = '许昌';
        _sa[41][4111] = '漯河';
        _sa[41][4112] = '三门峡';
        _sa[41][4113] = '南阳';
        _sa[41][4114] = '商丘';
        _sa[41][4115] = '信阳';
        _sa[41][4116] = '周口';
        _sa[41][4117] = '驻马店';
        _sa[41][4118] = '济源';
        _sa[41][4199] = '未识别地区';

        _sa[42][4200] = '请选择';
        _sa[42][4201] = '武汉';
        _sa[42][4202] = '黄石';
        _sa[42][4203] = '十堰';
        _sa[42][4205] = '宜昌';
        _sa[42][4206] = '襄樊';
        _sa[42][4207] = '鄂州';
        _sa[42][4208] = '荆门';
        _sa[42][4209] = '孝感';
        _sa[42][4210] = '荆州';
        _sa[42][4211] = '黄冈';
        _sa[42][4212] = '咸宁';
        _sa[42][4213] = '随州';
        _sa[42][4228] = '恩施';
        _sa[42][4229] = '仙桃';
        _sa[42][4230] = '潜江';
        _sa[42][4231] = '天门';
        _sa[42][4232] = '神农架';
        _sa[42][4299] = '未识别地区';

        _sa[43][4300] = '请选择';
        _sa[43][4301] = '长沙';
        _sa[43][4302] = '株洲';
        _sa[43][4303] = '湘潭';
        _sa[43][4304] = '衡阳';
        _sa[43][4305] = '邵阳';
        _sa[43][4306] = '岳阳';
        _sa[43][4307] = '常德';
        _sa[43][4308] = '张家界';
        _sa[43][4309] = '益阳';
        _sa[43][4310] = '郴州';
        _sa[43][4311] = '永州';
        _sa[43][4312] = '怀化';
        _sa[43][4313] = '娄底';
        _sa[43][4331] = '湘西';
        _sa[43][4399] = '未识别地区';

        _sa[44][4400] = '请选择';
        _sa[44][4401] = '广州';
        _sa[44][4402] = '韶关';
        _sa[44][4403] = '深圳';
        _sa[44][4404] = '珠海';
        _sa[44][4405] = '汕头';
        _sa[44][4406] = '佛山';
        _sa[44][4407] = '江门';
        _sa[44][4408] = '湛江';
        _sa[44][4409] = '茂名';
        _sa[44][4412] = '肇庆';
        _sa[44][4413] = '惠州';
        _sa[44][4414] = '梅州';
        _sa[44][4415] = '汕尾';
        _sa[44][4416] = '河源';
        _sa[44][4417] = '阳江';
        _sa[44][4418] = '清远';
        _sa[44][4419] = '东莞';
        _sa[44][4420] = '中山';
        _sa[44][4451] = '潮州';
        _sa[44][4452] = '揭阳';
        _sa[44][4453] = '云浮';
        _sa[44][4499] = '未识别地区';


        _sa[45][4500] = '请选择';
        _sa[45][4501] = '南宁';
        _sa[45][4502] = '柳州';
        _sa[45][4503] = '桂林';
        _sa[45][4504] = '梧州';
        _sa[45][4505] = '北海';
        _sa[45][4506] = '防城港';
        _sa[45][4507] = '钦州';
        _sa[45][4508] = '贵港';
        _sa[45][4509] = '玉林';
        _sa[45][4510] = '百色';
        _sa[45][4511] = '贺州';
        _sa[45][4512] = '河池';
        _sa[45][4513] = '来宾';
        _sa[45][4514] = '崇左';
        _sa[45][4599] = '未识别地区';

        _sa[46][4600] = '请选择';
        _sa[46][4601] = '海口';
        _sa[46][4602] = '三亚';
        _sa[46][4603] = '五指山';
        _sa[46][4604] = '琼海';
        _sa[46][4605] = '儋州';
        _sa[46][4606] = '文昌';
        _sa[46][4607] = '万宁';
        _sa[46][4608] = '东方';
        _sa[46][4621] = '定安县';
        _sa[46][4623] = '澄迈县';
        _sa[46][4624] = '临高县';
        _sa[46][4625] = '白沙黎族自治县';
        _sa[46][4626] = '昌江黎族自治县';
        _sa[46][4628] = '陵水黎族自治县';
        _sa[46][4629] = '保亭黎族苗族自治县';
        _sa[46][4699] = '未识别地区';

        _sa[50][5000] = '请选择';
        _sa[50][5001] = '重庆';

        _sa[51][5100] = '请选择';
        _sa[51][5101] = '成都';
        _sa[51][5103] = '自贡';
        _sa[51][5104] = '攀枝花';
        _sa[51][5105] = '泸州';
        _sa[51][5106] = '德阳';
        _sa[51][5107] = '绵阳';
        _sa[51][5108] = '广元';
        _sa[51][5109] = '遂宁';
        _sa[51][5110] = '内江';
        _sa[51][5111] = '乐山';
        _sa[51][5113] = '南充';
        _sa[51][5114] = '眉山';
        _sa[51][5115] = '宜宾';
        _sa[51][5116] = '广安';
        _sa[51][5117] = '达州';
        _sa[51][5118] = '雅安';
        _sa[51][5119] = '巴中';
        _sa[51][5120] = '资阳';
        _sa[51][5132] = '阿坝';
        _sa[51][5133] = '甘孜';
        _sa[51][5134] = '凉山';
        _sa[51][5199] = '未识别地区';

        _sa[52][5200] = '请选择';
        _sa[52][5201] = '贵阳';
        _sa[52][5202] = '六盘水';
        _sa[52][5203] = '遵义';
        _sa[52][5204] = '安顺';
        _sa[52][5222] = '铜仁';
        _sa[52][5223] = '黔西南';
        _sa[52][5224] = '毕节';
        _sa[52][5226] = '黔东南';
        _sa[52][5227] = '黔南';
        _sa[52][5299] = '未识别地区';

        _sa[53][5300] = '请选择';
        _sa[53][5301] = '昆明';
        _sa[53][5303] = '曲靖';
        _sa[53][5304] = '玉溪';
        _sa[53][5305] = '保山';
        _sa[53][5306] = '昭通';
        _sa[53][5307] = '丽江';
        _sa[53][5308] = '思茅';
        _sa[53][5309] = '临沧';
        _sa[53][5323] = '楚雄';
        _sa[53][5325] = '红河';
        _sa[53][5326] = '文山';
        _sa[53][5328] = '西双版纳';
        _sa[53][5329] = '大理';
        _sa[53][5331] = '德宏';
        _sa[53][5333] = '怒江傈';
        _sa[53][5334] = '迪庆';
        _sa[53][5399] = '未识别地区';

        _sa[54][5400] = '请选择';
        _sa[54][5401] = '拉萨';
        _sa[54][5421] = '昌都';
        _sa[54][5422] = '山南';
        _sa[54][5423] = '日喀则';
        _sa[54][5426] = '林芝';
        _sa[54][5499] = '未识别地区';

        _sa[61][6100] = '请选择';
        _sa[61][6101] = '西安';
        _sa[61][6102] = '铜川';
        _sa[61][6103] = '宝鸡';
        _sa[61][6104] = '咸阳';
        _sa[61][6105] = '渭南';
        _sa[61][6106] = '延安';
        _sa[61][6107] = '汉中';
        _sa[61][6108] = '榆林';
        _sa[61][6109] = '安康';
        _sa[61][6110] = '商洛';
        _sa[61][6199] = '未识别地区';

        _sa[62][6200] = '请选择';
        _sa[62][6201] = '兰州';
        _sa[62][6202] = '嘉峪关';
        _sa[62][6203] = '金昌';
        _sa[62][6204] = '白银';
        _sa[62][6205] = '天水';
        _sa[62][6206] = '武威';
        _sa[62][6207] = '张掖';
        _sa[62][6208] = '平凉';
        _sa[62][6209] = '酒泉';
        _sa[62][6210] = '庆阳';
        _sa[62][6211] = '定西';
        _sa[62][6212] = '陇南';
        _sa[62][6229] = '临夏';
        _sa[62][6230] = '甘南';
        _sa[62][6299] = '未识别地区';

        _sa[63][6300] = '请选择';
        _sa[63][6301] = '西宁';
        _sa[63][6321] = '海东';
        _sa[63][6322] = '海北';
        _sa[63][6325] = '海南';
        _sa[63][6328] = '海西';
        _sa[63][6399] = '未识别地区';

        _sa[64][6400] = '请选择';
        _sa[64][6401] = '银川';
        _sa[64][6402] = '石嘴山';
        _sa[64][6403] = '吴忠';
        _sa[64][6404] = '固原';
        _sa[64][6499] = '未识别地区';

        _sa[65][6500] = '请选择';
        _sa[65][6501] = '乌鲁木齐';
        _sa[65][6502] = '克拉玛依';
        _sa[65][6521] = '吐鲁番';
        _sa[65][6522] = '哈密';
        _sa[65][6523] = '昌吉';
        _sa[65][6527] = '博尔塔拉';
        _sa[65][6528] = '巴音郭楞';
        _sa[65][6529] = '阿克苏';
        _sa[65][6531] = '喀什';
        _sa[65][6532] = '和田';
        _sa[65][6540] = '伊犁';
        _sa[65][6542] = '塔城';
        _sa[65][6543] = '阿勒泰';
        _sa[65][6544] = '石河子';
        _sa[65][6545] = '阿拉尔';
        _sa[65][6599] = '未识别地区';


        _sa[71][7100] = '请选择';
        _sa[71][7101] = '台北市';
        _sa[71][7102] = '高雄市';
        _sa[71][7104] = '台中市';
        _sa[71][7105] = '台南市';
        _sa[71][7106] = '新竹市';
        _sa[71][7107] = '嘉义市';
        _sa[71][7109] = '宜兰县';
        _sa[71][7111] = '桃园县';
        _sa[71][7114] = '彰化县';
        _sa[71][7115] = '南投县';
        _sa[71][7117] = '云林县';
        _sa[71][7120] = '屏东县';
        _sa[71][7121] = '台东县';
        _sa[71][7122] = '花莲县';
        _sa[71][7123] = '澎湖县';
        _sa[71][7199] = '未识别地区';

        _sa[81][8100] = '请选择';
        _sa[81][8101] = '香港';

        _sa[82][8200] = '请选择';
        _sa[82][8201] = '澳门';

        //98:国内其他，99:国外;
        _sa[99][9999] = '请选择';
        _sa[98][9899] = '请选择';

        var $ = function (id) {
            return document.getElementById(id);
        };
        /**
        * 清除select的选项
        * @param {String} id select控件的id
        * @return:  {Boolen} 
        */
        function clearSelect(id) {
            var sObj = $(id);
            if ((sObj == undefined) || (sObj.tagName.toUpperCase() != "SELECT")) {
                return false;
            }
            for (var i = sObj.length; i >= 0; i--) {
                sObj.options[i] = null;
            }
            return true;
        }
        /**
        * 设置select的选中选项
        * @param {String} id select控件的id
        * @param {String} v  select控件选项选中的值
        * @return:  {Boolen} 
        */
        function setSelect(id, v) {
            var sObj = $(id);
            if ((sObj == undefined) || (sObj.tagName.toUpperCase() != "SELECT")) {
                return false;
            }

            for (var i = 0; i < sObj.length; i++) {
                if (sObj.options[i].value == v) {
                    sObj.options[i].selected = true;
                }
            }
            return true;
        }

        /**
        * 增加select的选项
        * @param {String} id select控件的id
        * @param {String} txt  select控件选项的显示文字
        * @param {String} val  select选项的值
        * @param {Bool} selected  是否选中
        * @return:  {Boolen} 
        */
        function addSelectItem(id, txt, val, selected) {
            var sObj = $(id);
            if ((sObj == undefined) || (sObj.tagName.toUpperCase() != "SELECT")) {
                return false;
            }
            selected = selected || false;
            var opt = new Option(txt, val, false, false);
            sObj.options[sObj.options.length] = opt;
            opt.selected = selected;
            return true;
        }

        /**
        * 获得select的值
        * @param {String} id select控件的id
        * @return:  false 失败
        *			{String} 值
        */
        function getSingleSelectValueById(id) {
            var sObj = $(id);
            if ((sObj == undefined) || (sObj.tagName.toUpperCase() != "SELECT")) {
                return false;
            }

            return sObj.options[sObj.selectedIndex].value;
        }


        /**
        * 对外接口地域码，转为完整的地域名
        * @param {Number} code 相关的地域码
        * @param {String} delimiter 一级地区与二级地区的分隔符
        * @return:  {String} 
        */
        function areaCode2Str(code, delimiter) {
            code = code || 0;
            var re = /^[1-9]\d{3}$/;
            if ((code != 0) && (!re.test(code))) {
                return "";
            }
            var p = Math.floor(code / 100);
            if (!_a[p] || !_sa[p][code]) {
                return ""
            }
            if (!delimiter) delimiter = ""
            return (_a[p] + delimiter + _sa[p][code]);
        }

        /**
        *对外接口，地区联动初始化的接口
        * @param {String} p 一级地区select控件的id
        * @param {String} c 二级地区select控件的id
        * @param {String} sv 地区的数值
        * @return:  false 失败
        *			true  成功
        */
        function areaSelectInit(p, c, sv) {
            if (!clearSelect(p)) {
                return false;
            }
            sv = sv || 0;
            var re = /^[1-9]\d{3}$/;
            if ((sv != 0) && (!re.test(sv))) {
                return false;
            }
            var pv = Math.floor(sv / 100);
            var key;
            for (key in _a) {
                if (typeof (_a[key]) == "function") continue;
                if (pv == key) {
                    addSelectItem(p, _a[key], key, true);
                } else {
                    addSelectItem(p, _a[key], key);
                }
            }

            var subObj = _sa[pv];
            for (key in subObj) {
                if (typeof (subObj[key]) == "function") continue;
                if (sv == key) {
                    addSelectItem(c, subObj[key], key, true);
                } else {
                    addSelectItem(c, subObj[key], key);
                }
            }

            var sObj = $(p);
            if (window.attachEvent) {
                sObj.attachEvent('onchange', function () { setCity(p, c); });
            } else {
                sObj.addEventListener('change', function () { setCity(p, c); }, false);
            }

            return true;
        }

        /*+++++++++++++联动复选框的实现++++++*/


        /**
        *暂时对外接口，地区联动设置二级地区的接口
        *          在一级地区onchange事件时调用
        * @param {String} p 一级地区select控件的id
        * @param {String} c 二级地区select控件的id
        * @param {String} sv 二级地区的选中选项的值
        * @return:  {Boolen} 
        *			false 失败
        *			true 值
        */
        function setCity(p, c, sv) {
            var v = getSingleSelectValueById(p);
            clearSelect(c);
            if (!v) {
                addSelectItem(c, "请选择", "0");
                return false;
            }

            var v = parseInt(v);
            var subObj = _sa[v];
            if (subObj == undefined) {
                return false;
            }
            sv = sv || (v * 100);

            if (Math.floor(sv / 100) != v) {
                return false;
            }

            for (var key in subObj) {
                if (typeof (subObj[key]) == "function") continue;
                if (sv == key) {
                    addSelectItem(c, subObj[key], key, true);
                } else {
                    addSelectItem(c, subObj[key], key);
                }
            }

            return true;
        }

        QZFL = window.QZFL || {};
        QZFL.widget = QZFL.widget || {};
        var _me = QZFL.widget.areaSelect = QZFL.widget.areaSelect || {};
        _me.areaSelectInit = areaSelectInit;
        _me.areaCode2Str = areaCode2Str;
        _me.setCity = setCity;
        _me.getSingleSelectValueById = getSingleSelectValueById;
        _me.getCitysById = function (id) {
            //if ((id = (id+'')).length == 2) {
            if (parseInt(id) < 1000) {
                return _sa[id] || [];
            } else {
                return _sa[id.slice(0, 2)] || [];
            }
        };
        _me.getData = function (type) {
            if (type == 'province') {
                return _a;
            }
            if (type == 'city') {
                return _sa;
            }
            return null;
        }
    })();
}

function $fireEvent(dom,type,eType) {
	var	dom=$id(dom),
		type=type || "click",
		eType= eType || "MouseEvents";
    if(window.attachEvent) {
        dom.fireEvent('on' + type);
    }else{
        var e = document.createEvent(eType);
        e.initEvent(type,true,true);
        dom.dispatchEvent(e);
    }
};

function $SWFUpload(option){
    //全局变量中查找
    if(window.SWFUpload){
        return new window.SWFUpload(option);
    }
    
    //以下为源代码
    /* ******************* */
    /* Constructor & Init  */
    /* ******************* */
    var SWFUpload;
    if (SWFUpload == undefined){
	    SWFUpload = function(settings){
		    this.initSWFUpload(settings);
	    };
    }
    
    
    SWFUpload.prototype.initSWFUpload = function (settings) {
	    try {
		    this.customSettings = {};	// A container where developers can place their own settings associated with this instance.
		    this.settings = settings;
		    this.eventQueue = [];
		    this.movieName = "SWFUpload_" + SWFUpload.movieCount++;
		    this.movieElement = null;


		    // Setup global control tracking
		    SWFUpload.instances[this.movieName] = this;

		    // Load the settings.  Load the Flash movie.
		    this.initSettings();
		    this.loadFlash();
		    this.displayDebugInfo();
	    } catch (ex) {
		    delete SWFUpload.instances[this.movieName];
		    throw ex;
	    }
    };

    /* *************** */
    /* Static Members  */
    /* *************** */
    SWFUpload.copyRight=
    ["SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com",
     "SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilz閚 and Mammon Media and is released under the MIT License:",
     "http://www.opensource.org/licenses/mit-license.php",
     "SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilz閚 and Mammon Media and is released under the MIT License:",
     "http://www.opensource.org/licenses/mit-license.php",
     "SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License:",
     "http://www.opensource.org/licenses/mit-license.php"];
    SWFUpload.instances = {};
    SWFUpload.movieCount = 0;
    SWFUpload.version = "2.2.0 2009-03-25";
    SWFUpload.QUEUE_ERROR = {
	    QUEUE_LIMIT_EXCEEDED	  		: -100,
	    FILE_EXCEEDS_SIZE_LIMIT  		: -110,
	    ZERO_BYTE_FILE			  		: -120,
	    INVALID_FILETYPE		  		: -130
    };
    SWFUpload.UPLOAD_ERROR = {
	    HTTP_ERROR				  		: -200,
	    MISSING_UPLOAD_URL	      		: -210,
	    IO_ERROR				  		: -220,
	    SECURITY_ERROR			  		: -230,
	    UPLOAD_LIMIT_EXCEEDED	  		: -240,
	    UPLOAD_FAILED			  		: -250,
	    SPECIFIED_FILE_ID_NOT_FOUND		: -260,
	    FILE_VALIDATION_FAILED	  		: -270,
	    FILE_CANCELLED			  		: -280,
	    UPLOAD_STOPPED					: -290
    };
    SWFUpload.FILE_STATUS = {
	    QUEUED		 : -1,
	    IN_PROGRESS	 : -2,
	    ERROR		 : -3,
	    COMPLETE	 : -4,
	    CANCELLED	 : -5
    };
    SWFUpload.BUTTON_ACTION = {
	    SELECT_FILE  : -100,
	    SELECT_FILES : -110,
	    START_UPLOAD : -120
    };
    SWFUpload.CURSOR = {
	    ARROW : -1,
	    HAND : -2
    };
    SWFUpload.WINDOW_MODE = {
	    WINDOW : "window",
	    TRANSPARENT : "transparent",
	    OPAQUE : "opaque"
    };

    // Private: takes a URL, determines if it is relative and converts to an absolute URL
    // using the current site. Only processes the URL if it can, otherwise returns the URL untouched
    SWFUpload.completeURL = function(url) {
	    if (typeof(url) !== "string" || url.match(/^https?:\/\//i) || url.match(/^\//)) {
		    return url;
	    }
    	
	    var currentURL = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : "");
    	
	    var indexSlash = window.location.pathname.lastIndexOf("/");
	    if (indexSlash <= 0) {
		    path = "/";
	    } else {
		    path = window.location.pathname.substr(0, indexSlash) + "/";
	    }
    	
	    return /*currentURL +*/ path + url;
    	
    };


    /* ******************** */
    /* Instance Members  */
    /* ******************** */

    // Private: initSettings ensures that all the
    // settings are set, getting a default value if one was not assigned.
    SWFUpload.prototype.initSettings = function () {
	    this.ensureDefault = function (settingName, defaultValue) {
		    this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
	    };
    	
	    // Upload backend settings
	    this.ensureDefault("upload_url", "");
	    this.ensureDefault("preserve_relative_urls", false);
	    this.ensureDefault("file_post_name", "Filedata");
	    this.ensureDefault("post_params", {});
	    this.ensureDefault("use_query_string", false);
	    this.ensureDefault("requeue_on_error", false);
	    this.ensureDefault("http_success", []);
	    this.ensureDefault("assume_success_timeout", 0);
    	
	    // File Settings
	    this.ensureDefault("file_types", "*.*");
	    this.ensureDefault("file_types_description", "All Files");
	    this.ensureDefault("file_size_limit", 0);	// Default zero means "unlimited"
	    this.ensureDefault("file_upload_limit", 0);
	    this.ensureDefault("file_queue_limit", 0);

	    // Flash Settings
	    this.ensureDefault("flash_url", "swfupload.swf");
	    this.ensureDefault("prevent_swf_caching", true);
    	
	    // Button Settings
	    this.ensureDefault("button_image_url", "");
	    this.ensureDefault("button_width", 1);
	    this.ensureDefault("button_height", 1);
	    this.ensureDefault("button_text", "");
	    this.ensureDefault("button_text_style", "color: #000000; font-size: 16pt;");
	    this.ensureDefault("button_text_top_padding", 0);
	    this.ensureDefault("button_text_left_padding", 0);
	    this.ensureDefault("button_action", SWFUpload.BUTTON_ACTION.SELECT_FILES);
	    this.ensureDefault("button_disabled", false);
	    this.ensureDefault("button_placeholder_id", "");
	    this.ensureDefault("button_placeholder", null);
	    this.ensureDefault("button_cursor", SWFUpload.CURSOR.ARROW);
	    this.ensureDefault("button_window_mode", SWFUpload.WINDOW_MODE.WINDOW);
    	
	    // Debug Settings
	    this.ensureDefault("debug", false);
	    this.settings.debug_enabled = this.settings.debug;	// Here to maintain v2 API
    	
	    // Event Handlers
	    this.settings.return_upload_start_handler = this.returnUploadStart;
	    this.ensureDefault("swfupload_loaded_handler", null);
	    this.ensureDefault("file_dialog_start_handler", null);
	    this.ensureDefault("file_queued_handler", null);
	    this.ensureDefault("file_queue_error_handler", null);
	    this.ensureDefault("file_dialog_complete_handler", null);
    	
	    this.ensureDefault("upload_start_handler", null);
	    this.ensureDefault("upload_progress_handler", null);
	    this.ensureDefault("upload_error_handler", null);
	    this.ensureDefault("upload_success_handler", null);
	    this.ensureDefault("upload_complete_handler", null);
    	
	    this.ensureDefault("debug_handler", this.debugMessage);

	    this.ensureDefault("custom_settings", {});

	    // Other settings
	    this.customSettings = this.settings.custom_settings;
    	
	    // Update the flash url if needed
	    if (!!this.settings.prevent_swf_caching) {
		    this.settings.flash_url = this.settings.flash_url + (this.settings.flash_url.indexOf("?") < 0 ? "?" : "&") + "preventswfcaching=" + new Date().getTime();
	    }
    	
	    if (!this.settings.preserve_relative_urls) {
		    //this.settings.flash_url = SWFUpload.completeURL(this.settings.flash_url);	// Don't need to do this one since flash doesn't look at it
		    this.settings.upload_url = SWFUpload.completeURL(this.settings.upload_url);
		    this.settings.button_image_url = SWFUpload.completeURL(this.settings.button_image_url);
	    }
    	
	    delete this.ensureDefault;
    };

    // Private: loadFlash replaces the button_placeholder element with the flash movie.
    SWFUpload.prototype.loadFlash = function () {
	    var targetElement, tempParent;

	    // Make sure an element with the ID we are going to use doesn't already exist
	    if (document.getElementById(this.movieName) !== null) {
		    throw "ID " + this.movieName + " is already in use. The Flash Object could not be added";
	    }

	    // Get the element where we will be placing the flash movie
	    targetElement = document.getElementById(this.settings.button_placeholder_id) || this.settings.button_placeholder;

	    if (targetElement == undefined) {
		    throw "Could not find the placeholder element: " + this.settings.button_placeholder_id;
	    }

	    // Append the container and load the flash
	    tempParent = document.createElement("div");
	    tempParent.innerHTML = this.getFlashHTML();	// Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers)
	    targetElement.parentNode.replaceChild(tempParent.firstChild, targetElement);

	    // Fix IE Flash/Form bug
	    if (window[this.movieName] == undefined) {
		    window[this.movieName] = this.getMovieElement();
	    }
    	
    };

    // Private: getFlashHTML generates the object tag needed to embed the flash in to the document
    SWFUpload.prototype.getFlashHTML = function () {
	    // Flash Satay object syntax: http://www.alistapart.com/articles/flashsatay
	    return ['<object id="', this.movieName, '" type="application/x-shockwave-flash" data="', this.settings.flash_url, '" width="', this.settings.button_width, '" height="', this.settings.button_height, '" class="swfupload">',
				    '<param name="wmode" value="', this.settings.button_window_mode, '" />',
				    '<param name="movie" value="', this.settings.flash_url, '" />',
				    '<param name="quality" value="high" />',
				    '<param name="menu" value="false" />',
				    '<param name="allowScriptAccess" value="always" />',
				    '<param name="flashvars" value="' + this.getFlashVars() + '" />',
				    '</object>'].join("");
    };

    // Private: getFlashVars builds the parameter string that will be passed
    // to flash in the flashvars param.
    SWFUpload.prototype.getFlashVars = function () {
	    // Build a string from the post param object
	    var paramString = this.buildParamString();
	    var httpSuccessString = this.settings.http_success.join(",");
    	
	    // Build the parameter string
	    return ["movieName=", encodeURIComponent(this.movieName),
			    "&amp;uploadURL=", encodeURIComponent(this.settings.upload_url),
			    "&amp;useQueryString=", encodeURIComponent(this.settings.use_query_string),
			    "&amp;requeueOnError=", encodeURIComponent(this.settings.requeue_on_error),
			    "&amp;httpSuccess=", encodeURIComponent(httpSuccessString),
			    "&amp;assumeSuccessTimeout=", encodeURIComponent(this.settings.assume_success_timeout),
			    "&amp;params=", encodeURIComponent(paramString),
			    "&amp;filePostName=", encodeURIComponent(this.settings.file_post_name),
			    "&amp;fileTypes=", encodeURIComponent(this.settings.file_types),
			    "&amp;fileTypesDescription=", encodeURIComponent(this.settings.file_types_description),
			    "&amp;fileSizeLimit=", encodeURIComponent(this.settings.file_size_limit),
			    "&amp;fileUploadLimit=", encodeURIComponent(this.settings.file_upload_limit),
			    "&amp;fileQueueLimit=", encodeURIComponent(this.settings.file_queue_limit),
			    "&amp;debugEnabled=", encodeURIComponent(this.settings.debug_enabled),
			    "&amp;buttonImageURL=", encodeURIComponent(this.settings.button_image_url),
			    "&amp;buttonWidth=", encodeURIComponent(this.settings.button_width),
			    "&amp;buttonHeight=", encodeURIComponent(this.settings.button_height),
			    "&amp;buttonText=", encodeURIComponent(this.settings.button_text),
			    "&amp;buttonTextTopPadding=", encodeURIComponent(this.settings.button_text_top_padding),
			    "&amp;buttonTextLeftPadding=", encodeURIComponent(this.settings.button_text_left_padding),
			    "&amp;buttonTextStyle=", encodeURIComponent(this.settings.button_text_style),
			    "&amp;buttonAction=", encodeURIComponent(this.settings.button_action),
			    "&amp;buttonDisabled=", encodeURIComponent(this.settings.button_disabled),
			    "&amp;buttonCursor=", encodeURIComponent(this.settings.button_cursor)
		    ].join("");
    };

    // Public: getMovieElement retrieves the DOM reference to the Flash element added by SWFUpload
    // The element is cached after the first lookup
    SWFUpload.prototype.getMovieElement = function () {
	    if (this.movieElement == undefined) {
		    this.movieElement = document.getElementById(this.movieName);
	    }

	    if (this.movieElement === null) {
		    throw "Could not find Flash element";
	    }
    	
	    return this.movieElement;
    };

    // Private: buildParamString takes the name/value pairs in the post_params setting object
    // and joins them up in to a string formatted "name=value&amp;name=value"
    SWFUpload.prototype.buildParamString = function () {
	    var postParams = this.settings.post_params; 
	    var paramStringPairs = [];

	    if (typeof(postParams) === "object") {
		    for (var name in postParams) {
			    if (postParams.hasOwnProperty(name)) {
				    paramStringPairs.push(encodeURIComponent(name.toString()) + "=" + encodeURIComponent(postParams[name].toString()));
			    }
		    }
	    }

	    return paramStringPairs.join("&amp;");
    };

    // Public: Used to remove a SWFUpload instance from the page. This method strives to remove
    // all references to the SWF, and other objects so memory is properly freed.
    // Returns true if everything was destroyed. Returns a false if a failure occurs leaving SWFUpload in an inconsistant state.
    // Credits: Major improvements provided by steffen
    SWFUpload.prototype.destroy = function () {
	    try {
		    // Make sure Flash is done before we try to remove it
		    this.cancelUpload(null, false);
    		

		    // Remove the SWFUpload DOM nodes
		    var movieElement = null;
		    movieElement = this.getMovieElement();
    		
		    if (movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE
			    // Loop through all the movie's properties and remove all function references (DOM/JS IE 6/7 memory leak workaround)
			    for (var i in movieElement) {
				    try {
					    if (typeof(movieElement[i]) === "function") {
						    movieElement[i] = null;
					    }
				    } catch (ex1) {}
			    }

			    // Remove the Movie Element from the page
			    try {
				    movieElement.parentNode.removeChild(movieElement);
			    } catch (ex) {}
		    }
    		
		    // Remove IE form fix reference
		    window[this.movieName] = null;

		    // Destroy other references
		    SWFUpload.instances[this.movieName] = null;
		    delete SWFUpload.instances[this.movieName];

		    this.movieElement = null;
		    this.settings = null;
		    this.customSettings = null;
		    this.eventQueue = null;
		    this.movieName = null;
    		
    		
		    return true;
	    } catch (ex2) {
		    return false;
	    }
    };


    // Public: displayDebugInfo prints out settings and configuration
    // information about this SWFUpload instance.
    // This function (and any references to it) can be deleted when placing
    // SWFUpload in production.
    SWFUpload.prototype.displayDebugInfo = function () {
	    this.debug(
		    [
			    "---SWFUpload Instance Info---\n",
			    "Version: ", SWFUpload.version, "\n",
			    "Movie Name: ", this.movieName, "\n",
			    "Settings:\n",
			    "\t", "upload_url:               ", this.settings.upload_url, "\n",
			    "\t", "flash_url:                ", this.settings.flash_url, "\n",
			    "\t", "use_query_string:         ", this.settings.use_query_string.toString(), "\n",
			    "\t", "requeue_on_error:         ", this.settings.requeue_on_error.toString(), "\n",
			    "\t", "http_success:             ", this.settings.http_success.join(", "), "\n",
			    "\t", "assume_success_timeout:   ", this.settings.assume_success_timeout, "\n",
			    "\t", "file_post_name:           ", this.settings.file_post_name, "\n",
			    "\t", "post_params:              ", this.settings.post_params.toString(), "\n",
			    "\t", "file_types:               ", this.settings.file_types, "\n",
			    "\t", "file_types_description:   ", this.settings.file_types_description, "\n",
			    "\t", "file_size_limit:          ", this.settings.file_size_limit, "\n",
			    "\t", "file_upload_limit:        ", this.settings.file_upload_limit, "\n",
			    "\t", "file_queue_limit:         ", this.settings.file_queue_limit, "\n",
			    "\t", "debug:                    ", this.settings.debug.toString(), "\n",

			    "\t", "prevent_swf_caching:      ", this.settings.prevent_swf_caching.toString(), "\n",

			    "\t", "button_placeholder_id:    ", this.settings.button_placeholder_id.toString(), "\n",
			    "\t", "button_placeholder:       ", (this.settings.button_placeholder ? "Set" : "Not Set"), "\n",
			    "\t", "button_image_url:         ", this.settings.button_image_url.toString(), "\n",
			    "\t", "button_width:             ", this.settings.button_width.toString(), "\n",
			    "\t", "button_height:            ", this.settings.button_height.toString(), "\n",
			    "\t", "button_text:              ", this.settings.button_text.toString(), "\n",
			    "\t", "button_text_style:        ", this.settings.button_text_style.toString(), "\n",
			    "\t", "button_text_top_padding:  ", this.settings.button_text_top_padding.toString(), "\n",
			    "\t", "button_text_left_padding: ", this.settings.button_text_left_padding.toString(), "\n",
			    "\t", "button_action:            ", this.settings.button_action.toString(), "\n",
			    "\t", "button_disabled:          ", this.settings.button_disabled.toString(), "\n",

			    "\t", "custom_settings:          ", this.settings.custom_settings.toString(), "\n",
			    "Event Handlers:\n",
			    "\t", "swfupload_loaded_handler assigned:  ", (typeof this.settings.swfupload_loaded_handler === "function").toString(), "\n",
			    "\t", "file_dialog_start_handler assigned: ", (typeof this.settings.file_dialog_start_handler === "function").toString(), "\n",
			    "\t", "file_queued_handler assigned:       ", (typeof this.settings.file_queued_handler === "function").toString(), "\n",
			    "\t", "file_queue_error_handler assigned:  ", (typeof this.settings.file_queue_error_handler === "function").toString(), "\n",
			    "\t", "upload_start_handler assigned:      ", (typeof this.settings.upload_start_handler === "function").toString(), "\n",
			    "\t", "upload_progress_handler assigned:   ", (typeof this.settings.upload_progress_handler === "function").toString(), "\n",
			    "\t", "upload_error_handler assigned:      ", (typeof this.settings.upload_error_handler === "function").toString(), "\n",
			    "\t", "upload_success_handler assigned:    ", (typeof this.settings.upload_success_handler === "function").toString(), "\n",
			    "\t", "upload_complete_handler assigned:   ", (typeof this.settings.upload_complete_handler === "function").toString(), "\n",
			    "\t", "debug_handler assigned:             ", (typeof this.settings.debug_handler === "function").toString(), "\n"
		    ].join("")
	    );
    };

    /* Note: addSetting and getSetting are no longer used by SWFUpload but are included
	    the maintain v2 API compatibility
    */
    // Public: (Deprecated) addSetting adds a setting value. If the value given is undefined or null then the default_value is used.
    SWFUpload.prototype.addSetting = function (name, value, default_value) {
        if (value == undefined) {
            return (this.settings[name] = default_value);
        } else {
            return (this.settings[name] = value);
	    }
    };

    // Public: (Deprecated) getSetting gets a setting. Returns an empty string if the setting was not found.
    SWFUpload.prototype.getSetting = function (name) {
        if (this.settings[name] != undefined) {
            return this.settings[name];
	    }

        return "";
    };



    // Private: callFlash handles function calls made to the Flash element.
    // Calls are made with a setTimeout for some functions to work around
    // bugs in the ExternalInterface library.
    SWFUpload.prototype.callFlash = function (functionName, argumentArray) {
	    argumentArray = argumentArray || [];
    	
	    var movieElement = this.getMovieElement();
	    var returnValue, returnString;

	    // Flash's method if calling ExternalInterface methods (code adapted from MooTools).
	    try {
		    returnString = movieElement.CallFunction('<invoke name="' + functionName + '" returntype="javascript">' + __flash__argumentsToXML(argumentArray, 0) + '</invoke>');
		    returnValue = eval(returnString);
	    } catch (ex) {
		    throw "Call to " + functionName + " failed";
	    }
    	
	    // Unescape file post param values
	    if (returnValue != undefined && typeof returnValue.post === "object") {
		    returnValue = this.unescapeFilePostParams(returnValue);
	    }

	    return returnValue;
    };

    /* *****************************
	    -- Flash control methods --
	    Your UI should use these
	    to operate SWFUpload
       ***************************** */

    // WARNING: this function does not work in Flash Player 10
    // Public: selectFile causes a File Selection Dialog window to appear.  This
    // dialog only allows 1 file to be selected.
    SWFUpload.prototype.selectFile = function () {
	    this.callFlash("SelectFile");
    };

    // WARNING: this function does not work in Flash Player 10
    // Public: selectFiles causes a File Selection Dialog window to appear/ This
    // dialog allows the user to select any number of files
    // Flash Bug Warning: Flash limits the number of selectable files based on the combined length of the file names.
    // If the selection name length is too long the dialog will fail in an unpredictable manner.  There is no work-around
    // for this bug.
    SWFUpload.prototype.selectFiles = function () {
	    this.callFlash("SelectFiles");
    };


    // Public: startUpload starts uploading the first file in the queue unless
    // the optional parameter 'fileID' specifies the ID 
    SWFUpload.prototype.startUpload = function (fileID) {
	    this.callFlash("StartUpload", [fileID]);
    };

    // Public: cancelUpload cancels any queued file.  The fileID parameter may be the file ID or index.
    // If you do not specify a fileID the current uploading file or first file in the queue is cancelled.
    // If you do not want the uploadError event to trigger you can specify false for the triggerErrorEvent parameter.
    SWFUpload.prototype.cancelUpload = function (fileID, triggerErrorEvent) {
	    if (triggerErrorEvent !== false) {
		    triggerErrorEvent = true;
	    }
	    this.callFlash("CancelUpload", [fileID, triggerErrorEvent]);
    };

    // Public: stopUpload stops the current upload and requeues the file at the beginning of the queue.
    // If nothing is currently uploading then nothing happens.
    SWFUpload.prototype.stopUpload = function () {
	    this.callFlash("StopUpload");
    };

    /* ************************
     * Settings methods
     *   These methods change the SWFUpload settings.
     *   SWFUpload settings should not be changed directly on the settings object
     *   since many of the settings need to be passed to Flash in order to take
     *   effect.
     * *********************** */

    // Public: getStats gets the file statistics object.
    SWFUpload.prototype.getStats = function () {
	    return this.callFlash("GetStats");
    };

    // Public: setStats changes the SWFUpload statistics.  You shouldn't need to 
    // change the statistics but you can.  Changing the statistics does not
    // affect SWFUpload accept for the successful_uploads count which is used
    // by the upload_limit setting to determine how many files the user may upload.
    SWFUpload.prototype.setStats = function (statsObject) {
	    this.callFlash("SetStats", [statsObject]);
    };

    // Public: getFile retrieves a File object by ID or Index.  If the file is
    // not found then 'null' is returned.
    SWFUpload.prototype.getFile = function (fileID) {
	    if (typeof(fileID) === "number") {
		    return this.callFlash("GetFileByIndex", [fileID]);
	    } else {
		    return this.callFlash("GetFile", [fileID]);
	    }
    };

    // Public: addFileParam sets a name/value pair that will be posted with the
    // file specified by the Files ID.  If the name already exists then the
    // exiting value will be overwritten.
    SWFUpload.prototype.addFileParam = function (fileID, name, value) {
	    return this.callFlash("AddFileParam", [fileID, name, value]);
    };

    // Public: removeFileParam removes a previously set (by addFileParam) name/value
    // pair from the specified file.
    SWFUpload.prototype.removeFileParam = function (fileID, name) {
	    this.callFlash("RemoveFileParam", [fileID, name]);
    };

    // Public: setUploadUrl changes the upload_url setting.
    SWFUpload.prototype.setUploadURL = function (url) {
	    this.settings.upload_url = url.toString();
	    this.callFlash("SetUploadURL", [url]);
    };

    // Public: setPostParams changes the post_params setting
    SWFUpload.prototype.setPostParams = function (paramsObject) {
	    this.settings.post_params = paramsObject;
	    this.callFlash("SetPostParams", [paramsObject]);
    };

    // Public: addPostParam adds post name/value pair.  Each name can have only one value.
    SWFUpload.prototype.addPostParam = function (name, value) {
	    this.settings.post_params[name] = value;
	    this.callFlash("SetPostParams", [this.settings.post_params]);
    };

    // Public: removePostParam deletes post name/value pair.
    SWFUpload.prototype.removePostParam = function (name) {
	    delete this.settings.post_params[name];
	    this.callFlash("SetPostParams", [this.settings.post_params]);
    };

    // Public: setFileTypes changes the file_types setting and the file_types_description setting
    SWFUpload.prototype.setFileTypes = function (types, description) {
	    this.settings.file_types = types;
	    this.settings.file_types_description = description;
	    this.callFlash("SetFileTypes", [types, description]);
    };

    // Public: setFileSizeLimit changes the file_size_limit setting
    SWFUpload.prototype.setFileSizeLimit = function (fileSizeLimit) {
	    this.settings.file_size_limit = fileSizeLimit;
	    this.callFlash("SetFileSizeLimit", [fileSizeLimit]);
    };

    // Public: setFileUploadLimit changes the file_upload_limit setting
    SWFUpload.prototype.setFileUploadLimit = function (fileUploadLimit) {
	    this.settings.file_upload_limit = fileUploadLimit;
	    this.callFlash("SetFileUploadLimit", [fileUploadLimit]);
    };

    // Public: setFileQueueLimit changes the file_queue_limit setting
    SWFUpload.prototype.setFileQueueLimit = function (fileQueueLimit) {
	    this.settings.file_queue_limit = fileQueueLimit;
	    this.callFlash("SetFileQueueLimit", [fileQueueLimit]);
    };

    // Public: setFilePostName changes the file_post_name setting
    SWFUpload.prototype.setFilePostName = function (filePostName) {
	    this.settings.file_post_name = filePostName;
	    this.callFlash("SetFilePostName", [filePostName]);
    };

    // Public: setUseQueryString changes the use_query_string setting
    SWFUpload.prototype.setUseQueryString = function (useQueryString) {
	    this.settings.use_query_string = useQueryString;
	    this.callFlash("SetUseQueryString", [useQueryString]);
    };

    // Public: setRequeueOnError changes the requeue_on_error setting
    SWFUpload.prototype.setRequeueOnError = function (requeueOnError) {
	    this.settings.requeue_on_error = requeueOnError;
	    this.callFlash("SetRequeueOnError", [requeueOnError]);
    };

    // Public: setHTTPSuccess changes the http_success setting
    SWFUpload.prototype.setHTTPSuccess = function (http_status_codes) {
	    if (typeof http_status_codes === "string") {
		    http_status_codes = http_status_codes.replace(" ", "").split(",");
	    }
    	
	    this.settings.http_success = http_status_codes;
	    this.callFlash("SetHTTPSuccess", [http_status_codes]);
    };

    // Public: setHTTPSuccess changes the http_success setting
    SWFUpload.prototype.setAssumeSuccessTimeout = function (timeout_seconds) {
	    this.settings.assume_success_timeout = timeout_seconds;
	    this.callFlash("SetAssumeSuccessTimeout", [timeout_seconds]);
    };

    // Public: setDebugEnabled changes the debug_enabled setting
    SWFUpload.prototype.setDebugEnabled = function (debugEnabled) {
	    this.settings.debug_enabled = debugEnabled;
	    this.callFlash("SetDebugEnabled", [debugEnabled]);
    };

    // Public: setButtonImageURL loads a button image sprite
    SWFUpload.prototype.setButtonImageURL = function (buttonImageURL) {
	    if (buttonImageURL == undefined) {
		    buttonImageURL = "";
	    }
    	
	    this.settings.button_image_url = buttonImageURL;
	    this.callFlash("SetButtonImageURL", [buttonImageURL]);
    };

    // Public: setButtonDimensions resizes the Flash Movie and button
    SWFUpload.prototype.setButtonDimensions = function (width, height) {
	    this.settings.button_width = width;
	    this.settings.button_height = height;
    	
	    var movie = this.getMovieElement();
	    if (movie != undefined) {
		    movie.style.width = width + "px";
		    movie.style.height = height + "px";
	    }
    	
	    this.callFlash("SetButtonDimensions", [width, height]);
    };
    // Public: setButtonText Changes the text overlaid on the button
    SWFUpload.prototype.setButtonText = function (html) {
	    this.settings.button_text = html;
	    this.callFlash("SetButtonText", [html]);
    };
    // Public: setButtonTextPadding changes the top and left padding of the text overlay
    SWFUpload.prototype.setButtonTextPadding = function (left, top) {
	    this.settings.button_text_top_padding = top;
	    this.settings.button_text_left_padding = left;
	    this.callFlash("SetButtonTextPadding", [left, top]);
    };

    // Public: setButtonTextStyle changes the CSS used to style the HTML/Text overlaid on the button
    SWFUpload.prototype.setButtonTextStyle = function (css) {
	    this.settings.button_text_style = css;
	    this.callFlash("SetButtonTextStyle", [css]);
    };
    // Public: setButtonDisabled disables/enables the button
    SWFUpload.prototype.setButtonDisabled = function (isDisabled) {
	    this.settings.button_disabled = isDisabled;
	    this.callFlash("SetButtonDisabled", [isDisabled]);
    };
    // Public: setButtonAction sets the action that occurs when the button is clicked
    SWFUpload.prototype.setButtonAction = function (buttonAction) {
	    this.settings.button_action = buttonAction;
	    this.callFlash("SetButtonAction", [buttonAction]);
    };

    // Public: setButtonCursor changes the mouse cursor displayed when hovering over the button
    SWFUpload.prototype.setButtonCursor = function (cursor) {
	    this.settings.button_cursor = cursor;
	    this.callFlash("SetButtonCursor", [cursor]);
    };

    /* *******************************
	    Flash Event Interfaces
	    These functions are used by Flash to trigger the various
	    events.
    	
	    All these functions a Private.
    	
	    Because the ExternalInterface library is buggy the event calls
	    are added to a queue and the queue then executed by a setTimeout.
	    This ensures that events are executed in a determinate order and that
	    the ExternalInterface bugs are avoided.
    ******************************* */

    SWFUpload.prototype.queueEvent = function (handlerName, argumentArray) {
	    // Warning: Don't call this.debug inside here or you'll create an infinite loop
    	
	    if (argumentArray == undefined) {
		    argumentArray = [];
	    } else if (!(argumentArray instanceof Array)) {
		    argumentArray = [argumentArray];
	    }
    	
	    var self = this;
	    if (typeof this.settings[handlerName] === "function") {
		    // Queue the event
		    this.eventQueue.push(function () {
			    this.settings[handlerName].apply(this, argumentArray);
		    });
    		
		    // Execute the next queued event
		    setTimeout(function () {
			    self.executeNextEvent();
		    }, 0);
    		
	    } else if (this.settings[handlerName] !== null) {
		    throw "Event handler " + handlerName + " is unknown or is not a function";
	    }
    };

    // Private: Causes the next event in the queue to be executed.  Since events are queued using a setTimeout
    // we must queue them in order to garentee that they are executed in order.
    SWFUpload.prototype.executeNextEvent = function () {
	    // Warning: Don't call this.debug inside here or you'll create an infinite loop

	    var  f = this.eventQueue ? this.eventQueue.shift() : null;
	    if (typeof(f) === "function") {
		    f.apply(this);
	    }
    };

    // Private: unescapeFileParams is part of a workaround for a flash bug where objects passed through ExternalInterface cannot have
    // properties that contain characters that are not valid for JavaScript identifiers. To work around this
    // the Flash Component escapes the parameter names and we must unescape again before passing them along.
    SWFUpload.prototype.unescapeFilePostParams = function (file) {
	    var reg = /[$]([0-9a-f]{4})/i;
	    var unescapedPost = {};
	    var uk;

	    if (file != undefined) {
		    for (var k in file.post) {
			    if (file.post.hasOwnProperty(k)) {
				    uk = k;
				    var match;
				    while ((match = reg.exec(uk)) !== null) {
					    uk = uk.replace(match[0], String.fromCharCode(parseInt("0x" + match[1], 16)));
				    }
				    unescapedPost[uk] = file.post[k];
			    }
		    }

		    file.post = unescapedPost;
	    }

	    return file;
    };

    // Private: Called by Flash to see if JS can call in to Flash (test if External Interface is working)
    SWFUpload.prototype.testExternalInterface = function () {
	    try {
		    return this.callFlash("TestExternalInterface");
	    } catch (ex) {
		    return false;
	    }
    };

    // Private: This event is called by Flash when it has finished loading. Don't modify this.
    // Use the swfupload_loaded_handler event setting to execute custom code when SWFUpload has loaded.
    SWFUpload.prototype.flashReady = function () {
	    // Check that the movie element is loaded correctly with its ExternalInterface methods defined
	    var movieElement = this.getMovieElement();

	    if (!movieElement) {
		    this.debug("Flash called back ready but the flash movie can't be found.");
		    return;
	    }

	    this.cleanUp(movieElement);
    	
	    this.queueEvent("swfupload_loaded_handler");
    };

    // Private: removes Flash added fuctions to the DOM node to prevent memory leaks in IE.
    // This function is called by Flash each time the ExternalInterface functions are created.
    SWFUpload.prototype.cleanUp = function (movieElement) {
	    // Pro-actively unhook all the Flash functions
	    try {
		    if (this.movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE
			    this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");
			    for (var key in movieElement) {
				    try {
					    if (typeof(movieElement[key]) === "function") {
						    movieElement[key] = null;
					    }
				    } catch (ex) {
				    }
			    }
		    }
	    } catch (ex1) {
    	
	    }

	    // Fix Flashes own cleanup code so if the SWFMovie was removed from the page
	    // it doesn't display errors.
	    window["__flash__removeCallback"] = function (instance, name) {
		    try {
			    if (instance) {
				    instance[name] = null;
			    }
		    } catch (flashEx) {
    		
		    }
	    };

    };


    /* This is a chance to do something before the browse window opens */
    SWFUpload.prototype.fileDialogStart = function () {
	    this.queueEvent("file_dialog_start_handler");
    };


    /* Called when a file is successfully added to the queue. */
    SWFUpload.prototype.fileQueued = function (file) {
	    file = this.unescapeFilePostParams(file);
	    this.queueEvent("file_queued_handler", file);
    };


    /* Handle errors that occur when an attempt to queue a file fails. */
    SWFUpload.prototype.fileQueueError = function (file, errorCode, message) {
	    file = this.unescapeFilePostParams(file);
	    this.queueEvent("file_queue_error_handler", [file, errorCode, message]);
    };

    /* Called after the file dialog has closed and the selected files have been queued.
	    You could call startUpload here if you want the queued files to begin uploading immediately. */
    SWFUpload.prototype.fileDialogComplete = function (numFilesSelected, numFilesQueued, numFilesInQueue) {
	    this.queueEvent("file_dialog_complete_handler", [numFilesSelected, numFilesQueued, numFilesInQueue]);
    };

    SWFUpload.prototype.uploadStart = function (file) {
	    file = this.unescapeFilePostParams(file);
	    this.queueEvent("return_upload_start_handler", file);
    };

    SWFUpload.prototype.returnUploadStart = function (file) {
	    var returnValue;
	    if (typeof this.settings.upload_start_handler === "function") {
		    file = this.unescapeFilePostParams(file);
		    returnValue = this.settings.upload_start_handler.call(this, file);
	    } else if (this.settings.upload_start_handler != undefined) {
		    throw "upload_start_handler must be a function";
	    }

	    // Convert undefined to true so if nothing is returned from the upload_start_handler it is
	    // interpretted as 'true'.
	    if (returnValue === undefined) {
		    returnValue = true;
	    }
    	
	    returnValue = !!returnValue;
    	
	    this.callFlash("ReturnUploadStart", [returnValue]);
    };



    SWFUpload.prototype.uploadProgress = function (file, bytesComplete, bytesTotal) {
	    file = this.unescapeFilePostParams(file);
	    this.queueEvent("upload_progress_handler", [file, bytesComplete, bytesTotal]);
    };

    SWFUpload.prototype.uploadError = function (file, errorCode, message) {
	    file = this.unescapeFilePostParams(file);
	    this.queueEvent("upload_error_handler", [file, errorCode, message]);
    };

    SWFUpload.prototype.uploadSuccess = function (file, serverData, responseReceived) {
	    file = this.unescapeFilePostParams(file);
	    this.queueEvent("upload_success_handler", [file, serverData, responseReceived]);
    };

    SWFUpload.prototype.uploadComplete = function (file) {
	    file = this.unescapeFilePostParams(file);
	    this.queueEvent("upload_complete_handler", file);
    };

    /* Called by SWFUpload JavaScript and Flash functions when debug is enabled. By default it writes messages to the
       internal debug console.  You can override this event and have messages written where you want. */
    SWFUpload.prototype.debug = function (message) {
	    this.queueEvent("debug_handler", message);
    };


    /* **********************************
	    Debug Console
	    The debug console is a self contained, in page location
	    for debug message to be sent.  The Debug Console adds
	    itself to the body if necessary.

	    The console is automatically scrolled as messages appear.
    	
	    If you are using your own debug handler or when you deploy to production and
	    have debug disabled you can remove these functions to reduce the file size
	    and complexity.
    ********************************** */
       
    // Private: debugMessage is the default debug_handler.  If you want to print debug messages
    // call the debug() function.  When overriding the function your own function should
    // check to see if the debug setting is true before outputting debug information.
    SWFUpload.prototype.debugMessage = function (message) {
	    if (this.settings.debug) {
		    var exceptionMessage, exceptionValues = [];

		    // Check for an exception object and print it nicely
		    if (typeof message === "object" && typeof message.name === "string" && typeof message.message === "string") {
			    for (var key in message) {
				    if (message.hasOwnProperty(key)) {
					    exceptionValues.push(key + ": " + message[key]);
				    }
			    }
			    exceptionMessage = exceptionValues.join("\n") || "";
			    exceptionValues = exceptionMessage.split("\n");
			    exceptionMessage = "EXCEPTION: " + exceptionValues.join("\nEXCEPTION: ");
			    SWFUpload.Console.writeLine(exceptionMessage);
		    } else {
			    SWFUpload.Console.writeLine(message);
		    }
	    }
    };

    SWFUpload.Console = {};
    SWFUpload.Console.writeLine = function (message) {
	    var console, documentForm;

	    try {
		    console = document.getElementById("SWFUpload_Console");

		    if (!console) {
			    documentForm = document.createElement("form");
			    document.getElementsByTagName("body")[0].appendChild(documentForm);

			    console = document.createElement("textarea");
			    console.id = "SWFUpload_Console";
			    console.style.fontFamily = "monospace";
			    console.setAttribute("wrap", "off");
			    console.wrap = "off";
			    console.style.overflow = "auto";
			    console.style.width = "700px";
			    console.style.height = "350px";
			    console.style.margin = "5px";
			    documentForm.appendChild(console);
		    }

		    console.value += message + "\n";

		    console.scrollTop = console.scrollHeight - console.clientHeight;
	    } catch (ex) {
		    alert("Exception: " + ex.name + " Message: " + ex.message);
	    }
    };
    //源代码结束
    
    //保存在全局变量中
    window.SWFUpload= SWFUpload;
    return new window.SWFUpload(option);
 }

(function(){
	var _formatArray_cache = {};
	
	$formatArray=function(str, data){
   	 	/* 模板替换,str:模板id或者内容，data:数据内容
			\W：匹配任何非单词字符。等价于 '[^A-Za-z0-9_]'。 
			如果是id,并且cache中有值，直接返回，否则获取innerHTML，再次解析；
			如果不是id，解析并存入cache
		 */
		var fn = !/\W/.test(str)?
			_formatArray_cache[str]=_formatArray_cache[str] || $formatArray($id(str).innerHTML) :
				new Function("arr",
					"var p=[];p.push('" +str.replace(/[\r\t\n]/g, " ").split("<%")
					.join("\t").replace(/((^|%>)[^\t]*)'/g, "$1\r").replace(/\t=(.*?)%>/g, "',$1,'").split("\t")
					.join("');").split("%>")
					.join("p.push('").split("\r")
					.join("\\'") + "');return p.join('');");
		return data ? fn( data ) : fn;
	}
})();

function $urlEncode(str){
	if(str && str.length){
		return escape(str).replace(/\+/g, '%2B').replace(/\"/g,'%22').replace(/\'/g, '%27').replace(/\//g,'%2F');
	}
	return "";
}

/*
        * 图片预览
        * @el ：展示预览图片的容器
        * @fileInput ：上传控件对象
        * @callback ：预览回调事件（errCode：0为正常，-1为预览失败）
        * @maxWidth ：预览图片最大宽度
        * @maxHeight ：预览图片最大高度
        * @autoSize ：预览的图片是否自适应大小（如果为false，预览图片将以maxHeight，maxWidth的格式展示）
        */
        function $imgPreview(conf) {
            var _conf = {
                el: null,
                fileInput: null,
                callback: function (errCode) { },
                maxWidth: 160,
                maxHeight: 160,
                autoSize: false,
                acceptType: ['.jpg', '.gif']
            }
            var doc = document;
            for (var key in _conf) {
                conf[key] = conf[key] || _conf[key];
            }

            conf.el = typeof conf.el === 'string' ? doc.getElementById(conf.el) : conf.el;
            conf.fileInput = typeof conf.fileInput === 'string' ? doc.getElementById(conf.fileInput) : conf.fileInput;

            if (!conf.el || !conf.fileInput) {
                return false;
            }
            //绑定预览事件
            addEvent(conf.fileInput, 'change', setPreviewImg);

            //_imgSizeTest是一只小白鼠，用来测量上传图片的真实大小
            var prevHtml = '<div id="_preContent" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale);"></div>';
            if (conf.autoSize) {
                prevHtml += '<img id="_imgSizeTest" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=image);visibility:hidden;position:absolute;left : -' + (conf.maxHeight + 10000) + 'px;" />';
            }
            conf.el.innerHTML = prevHtml;
            //设置图片预览
            function setPreviewImg() {
                var obj = conf.fileInput,
                    reg = new RegExp(conf.acceptType.join('|'), 'i');
                if (!obj.value.match(reg)) {
                    alert('图片格式无效！');
                    conf.fileInput.value = '';
                    //清空file中的值，just for ie
                    (function clearFileInput(file) {
                        var form = document.createElement('form');
                        document.body.appendChild(form);
                        var pos = file.nextSibling;
                        form.appendChild(file);
                        form.reset();
                        pos.parentNode.insertBefore(file, pos);
                        document.body.removeChild(form);
                    })(conf.fileInput);
                    return false;
                }
                var _preContent = doc.getElementById('_preContent'),
                    _imgSizeTest = doc.getElementById('_imgSizeTest');
                    _preContent.innerHTML = '';
                var imgPrevObj = doc.createElement("img");
                    imgPrevObj.setAttribute("src", "");
                    imgPrevObj.setAttribute("id", "_preview");
                    _preContent.appendChild(imgPrevObj);
                //展示图片的对象引用
                var preObj,
					imgSrc;

                try {
                    if (isBrowser('ie')) {
                        if (isBrowser('ie6')) {
                            imgPrevObj.setAttribute("src", obj.value);
							imgSrc = obj.value;
                            preObj = imgPrevObj;
                        } else {
                            obj.select();
							imgSrc = doc.selection.createRange().text;
                            _preContent.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = imgSrc;
                            if (_imgSizeTest) {
                                _imgSizeTest.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = imgSrc;
                            }
                            imgPrevObj.style.display = 'none';
                            preObj = _preContent;
                        }
                    } else {
						imgSrc = obj.files[0].getAsDataURL();
                        imgPrevObj.setAttribute("src", imgSrc);
                        preObj = imgPrevObj;
                    }
                } catch (e) {
                    conf.callback(-1);
                    return false;
                }

                if (!conf.autoSize) {   //不允许自适应大小，直接赋值为最大的宽高值
                    preObj.style.width = conf.maxWidth + 'px';
                    preObj.style.height = conf.maxHeight + 'px';
                } else {
                    autoSizePreview(preObj, _imgSizeTest.offsetWidth, _imgSizeTest.offsetHeight);
                }

                conf.callback(0, {imgSrc:imgSrc});
            }
            function autoSizePreview(objPre, originalWidth, originalHeight) {
                var zoomParam = clacImgZoomParam(conf.maxWidth, conf.maxHeight, originalWidth, originalHeight);
                objPre.style.width = zoomParam.width + 'px';
                objPre.style.height = zoomParam.height + 'px';
            }
            function clacImgZoomParam(maxWidth, maxHeight, width, height) {
                var param = { width: width, height: height };

                if (width > maxWidth || height > maxHeight) {
                    rateWidth = width / maxWidth;
                    rateHeight = height / maxHeight;

                    if (rateWidth > rateHeight) {
                        param.width = maxWidth;
                        param.height = height / rateWidth;
                    } else {
                        param.width = width / rateHeight;
                        param.height = maxHeight;
                    }
                }
                return param;
            }
            function addEvent(obj, type, handle) {
                //事件绑定，兼容ff，ie
                if (window.addEventListener) {
                    obj.addEventListener(type, handle, false);
                } else if (window.attachEvent) {
                    obj.attachEvent("on" + type, handle);
                } else {
                    obj["on" + type] = handle;
                }
            };
            function isBrowser(str) {
                str = str.toLowerCase();
                var b = navigator.userAgent.toLowerCase();
                var arrB = [];
                arrB['firefox'] = b.indexOf("firefox") != -1;
                arrB['opera'] = b.indexOf("opera") != -1;
                arrB['safari'] = b.indexOf("safari") != -1;
                arrB['gecko'] = !arrB['opera'] && !arrB['safari'] && b.indexOf("gecko") > -1;
                arrB['ie'] = !arrB['opera'] && b.indexOf("msie") != -1;
                arrB['ie6'] = !arrB['opera'] && b.indexOf("msie 6") != -1;
                arrB['ie7'] = !arrB['opera'] && b.indexOf("msie 7") != -1;
                return arrB[str];
            };
    return {
        setImg: setPreviewImg
    }
        };

/**
* 校验文本框输入字数长度
*
* @param {string} text : 文本框对象id
* @param {number} minLen : 允许输入的最少字/字节数
* @param {number} maxLen : 允许输入的最多字/字节数
* @param {number} lenTxt : 展示输入字数的text对象
* @param {string} lengthRecord : 展示已输入字数和最大字符的div对象id
内部必须包含tag='num'的对象，用于展示当前输入的字数。
如：<div id="lengthRecord"><span tag="current"></span></div>
* @param {bool} isGb：是否区分中英文，默认为true
*/
function $getInputLen(conf) {
    var _conf = {
        text: null,
        minLen: 0,
        maxLen: 20,
        lengthRecord: null,
        isGb: true
    }
    _conf = $extend(_conf, conf);
    _conf.text = document.getElementById(_conf.text);
    _conf.lengthRecord = document.getElementById(_conf.lengthRecord);
    _conf.curNum = $attr('tag', 'current', _conf.lengthRecord)[0];

    var _checkLen = (function (c) {
        return function () {
            var str = c.text.value.replace(/(^\s*)|(\s*$)/g, ''),
            length = str.replace(/[\u00FF-\uFFFF]/g, "  ").length;

            if (c.isGb) {  //提示字
                if (((length + 3) >= c.minLen * 2) && (length < c.minLen * 2) && c.minLen) { //特殊处理下限字数的临界值
                    length = c.minLen - 1;
                } else {
                    length = length % 2 ? (length + 1) / 2 : length / 2;
                }
                if ((c.minLen && (length < c.minLen)) || (c.maxLen && (length > c.maxLen))) {
                    c.lengthRecord.style.color = "red";
                } else {
                    c.lengthRecord.style.color = "";
                }
            } else {            //提示字节
                if ((c.minLen && (length < c.minLen)) || (c.maxLen && (length > c.maxLen))) {
                    c.lengthRecord.style.color = "red";
                } else {
                    c.lengthRecord.style.color = "";
                }
            }
            c.curNum.innerHTML = length;
        }
    })(_conf);

    if (_conf.text.value.length > 0) {
        _checkLen();
    }

    //用户群名称文本框事件
    $addEvent(_conf.text, 'blur', _checkLen);
    $addEvent(_conf.text, 'keyup', _checkLen);
};


/**
* tab菜单切换控件
* @param {object} conf：自定义配置参数
    {array} tabs: 菜单对象数组
    {array} contents: 展示内容对象数组
    {string} activeStyle: 菜单激活样式
    {string} disableStyle: 菜单禁用样式
    {string} activeCStyle: 内容激活样式
    {string} disableCStyle: 内容禁用样式
    {number} defaultIndex: 默认激活的索引
    {string} event: 触发激活的菜单事件
    {string} menuTag: 菜单tagname
    {function} selected: 激活菜单后的事件
    {function} filter: 获取触发事件的对象方法
* @return {object} 返回接口对象
    {function} setActiveContent：设置激活的内容区
    {function} setActiveTab：设置激活的菜单
*/
function $expTabChange(conf) {
    var _conf = {
        tabs: [],
        contents: [],
        activeStyle: "",
        disableStyle: "",
        activeCStyle: "",
        disableCStyle: "none",
        defaultIndex: 0,
        event: 'click',
        menuTag: 'LI',
        selected: function (index, _conf) {
        },
        filter: function (e) {
            return e.srcElement || e.target;
        }
    }
    for (var key in conf) {
        if (conf[key]) {
            _conf[key] = conf[key];
        }
    }
    for (var i = 0, len = _conf.tabs.length; i < len; i++) {
        $addEvent(_conf.tabs[i], _conf.event, activeTab);
        if (_conf.contents[i]) {
            if (i != _conf.defaultIndex) {
                //disabled
                setStyle(_conf.contents[i], 2);
            }
            else {
                //active
                setStyle(_conf.contents[i], 1);
            }
        }
    }
    if (_conf.tabs[_conf.defaultIndex]) {
        //active
        setStyle(_conf.tabs[_conf.defaultIndex], 1, 'tab');
    }
    function activeTab(e) {
        var e = e || window.event;
        var self = _conf.filter(e), index;
        if (!self) { return; }
        //active
        setStyle(self, 1, 'tab');
        for (var i = 0, len = Math.max(_conf.tabs.length, _conf.contents.length); i < len; i++) {
            if (_conf.tabs[i] === self || _conf.tabs[i] == getMenu(self, _conf.menuTag)) {
                if (_conf.contents[i]) {
                    //active
                    setStyle(_conf.contents[i], 1);
                }
                index = i;
            }
            else {
                //disabled
                if (_conf.contents[i]) {
                    setStyle(_conf.contents[i], 2);
                }
                if (_conf.tabs[i]) {
                    setStyle(_conf.tabs[i], 2, 'tab');
                }
            }
        }
        _conf.selected(index, _conf);
    }
    //设置对象激活/禁用样式
    function setStyle(obj, type, tag) {
        var activestyle = _conf.activeCStyle, disabledstyle = _conf.disableCStyle;
        if (tag == 'tab') {
            if (obj.tagName.toLowerCase() != 'li') {
                obj = getMenu(obj.parentNode, _conf.menuTag)
                if (!obj) {
                    return false;
                }
            }
            activestyle = _conf.activeStyle;
            disabledstyle = _conf.disableStyle;
        }
        if (type == 1 || type == "active") {
            if (disabledstyle) {
                $delClass(obj, disabledstyle);
            }
            if (activestyle) {
                $addClass(obj, activestyle);
            }
        } else {
            if (activestyle) {
                $delClass(obj, activestyle);
            }
            if (disabledstyle) {
                $addClass(obj, disabledstyle);
            }
        }
    }
    function getMenu(obj, tag) {
        while (obj && obj.tagName && (obj.tagName.toLowerCase() != tag.toLowerCase())) {
            obj = obj.parentNode;
        }
        return obj;
    }
    return {
        setActiveTab: function (index) {
            for (var i = 0, len = _conf.tabs.length; i < len; i++) {
                if (_conf.tabs[i]) {
                    if (i != index) {
                        //disabled
                        setStyle(_conf.tabs[i], 2, 'tab');
                    }
                    else {
                        //active
                        setStyle(_conf.tabs[i], 1, 'tab');
                    }
                }
            }
        },
        setActiveContent: function (index) {
            for (var i = 0, len = _conf.contents.length; i < len; i++) {
                if (_conf.contents[i]) {
                    if (i != index) {
                        //disabled
                        setStyle(_conf.contents[i], 2);
                    }
                    else {
                        //active
                        setStyle(_conf.contents[i], 1);
                    }
                }
            }
        }
    }
};

/***********  End Core Function  ***********/